Java Thread 类
Thread 类是 Java 中用于创建和管理线程的核心类。
在 Java 中,每个线程都是 Thread 类的一个实例。线程可以理解为程序中独立执行的"子任务",它允许程序同时执行多个操作。
Java 中的线程有两种创建方式:
- 继承 Thread 类
- 实现 Runnable 接口
Thread 类的基本用法
创建线程
实例
// 方式1:继承 Thread 类
class MyThread extends Thread {
public void run() {
System.out.println("线程正在运行");
}
}
// 方式2:实现 Runnable 接口
class MyRunnable implements Runnable {
public void run() {
System.out.println("线程正在运行");
}
}
public class Main {
public static void main(String[] args) {
// 使用继承方式
MyThread thread1 = new MyThread();
thread1.start();
// 使用接口方式
Thread thread2 = new Thread(new MyRunnable());
thread2.start();
}
}
class MyThread extends Thread {
public void run() {
System.out.println("线程正在运行");
}
}
// 方式2:实现 Runnable 接口
class MyRunnable implements Runnable {
public void run() {
System.out.println("线程正在运行");
}
}
public class Main {
public static void main(String[] args) {
// 使用继承方式
MyThread thread1 = new MyThread();
thread1.start();
// 使用接口方式
Thread thread2 = new Thread(new MyRunnable());
thread2.start();
}
}
线程的生命周期
Java 线程有以下几种状态:
- NEW:新创建的线程,尚未调用 start() 方法
- RUNNABLE:可运行状态,可能在运行或等待 CPU 时间
- BLOCKED:线程被阻塞,等待获取监视器锁
- WAITING:等待状态,等待其他线程执行特定操作
- TIMED_WAITING:有限时间的等待状态
- TERMINATED:线程已终止
Thread 类的常用方法
基本控制方法
实例
Thread thread = new Thread(() -> {
System.out.println("线程执行中");
});
thread.start(); // 启动线程
thread.join(); // 等待线程结束
thread.sleep(1000); // 线程休眠1秒
System.out.println("线程执行中");
});
thread.start(); // 启动线程
thread.join(); // 等待线程结束
thread.sleep(1000); // 线程休眠1秒
线程优先级
实例
thread.setPriority(Thread.MAX_PRIORITY); // 最高优先级(10)
thread.setPriority(Thread.NORM_PRIORITY); // 默认优先级(5)
thread.setPriority(Thread.MIN_PRIORITY); // 最低优先级(1)
thread.setPriority(Thread.NORM_PRIORITY); // 默认优先级(5)
thread.setPriority(Thread.MIN_PRIORITY); // 最低优先级(1)
线程中断
实例
thread.interrupt(); // 中断线程
// 在线程中检查中断状态
if (Thread.interrupted()) {
// 处理中断逻辑
}
// 在线程中检查中断状态
if (Thread.interrupted()) {
// 处理中断逻辑
}
线程同步
当多个线程访问共享资源时,需要使用同步机制来避免数据不一致问题。
使用 synchronized 关键字
实例
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
}
private int count = 0;
public synchronized void increment() {
count++;
}
}
使用 Lock 接口
实例
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class Counter {
private int count = 0;
private Lock lock = new ReentrantLock();
public void increment() {
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
}
}
import java.util.concurrent.locks.ReentrantLock;
class Counter {
private int count = 0;
private Lock lock = new ReentrantLock();
public void increment() {
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
}
}
线程池与 Thread 类
在实际开发中,通常使用线程池来管理线程,而不是直接创建 Thread 对象。
实例
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolExample {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
executor.execute(() -> {
System.out.println("线程执行任务");
});
}
executor.shutdown();
}
}
import java.util.concurrent.Executors;
public class ThreadPoolExample {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
executor.execute(() -> {
System.out.println("线程执行任务");
});
}
executor.shutdown();
}
}
最佳实践
- 优先使用实现 Runnable 接口的方式创建线程
- 使用线程池管理线程资源
- 避免过度同步,只在必要时使用同步机制
- 使用 volatile 关键字确保变量的可见性
- 考虑使用 Java 并发包(java.util.concurrent)中的高级工具类
通过合理使用 Thread 类和相关并发工具,可以编写出高效、可靠的多线程 Java 程序。
点我分享笔记