java线程如何使用
线程的基本概念
Java线程是程序执行的最小单元,允许并发执行多个任务。每个线程都有自己的调用栈和程序计数器,共享进程的堆和方法区资源。
创建线程的方法
继承Thread类
通过继承Thread类并重写run()方法创建线程。实例化后调用start()方法启动线程。
class MyThread extends Thread {
public void run() {
System.out.println("Thread running");
}
}
MyThread thread = new MyThread();
thread.start();
实现Runnable接口
实现Runnable接口的run()方法,将实例作为参数传递给Thread构造函数。
class MyRunnable implements Runnable {
public void run() {
System.out.println("Runnable running");
}
}
Thread thread = new Thread(new MyRunnable());
thread.start();
使用Lambda表达式
Java 8后可通过Lambda简化Runnable实现。
Thread thread = new Thread(() -> {
System.out.println("Lambda thread running");
});
thread.start();
线程的生命周期
线程具有以下状态:
- NEW:创建但未启动
- RUNNABLE:可运行或正在运行
- BLOCKED:等待监视器锁
- WAITING:无限期等待其他线程操作
- TIMED_WAITING:有限时间等待
- TERMINATED:执行完成
线程同步与锁
synchronized关键字
使用synchronized修饰方法或代码块确保线程安全。

public synchronized void synchronizedMethod() {
// 线程安全代码
}
public void method() {
synchronized(this) {
// 同步代码块
}
}
ReentrantLock类 提供更灵活的锁机制,需手动释放锁。
ReentrantLock lock = new ReentrantLock();
lock.lock();
try {
// 临界区代码
} finally {
lock.unlock();
}
线程间通信
wait()和notify()
通过Object类的wait()和notify()实现线程间协调。
synchronized(sharedObject) {
while(conditionNotMet) {
sharedObject.wait();
}
// 执行操作
sharedObject.notifyAll();
}
BlockingQueue
使用BlockingQueue实现生产者-消费者模式。

BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10);
// 生产者
queue.put(1);
// 消费者
int value = queue.take();
线程池的使用
Executor框架
通过Executors工厂类创建线程池。
ExecutorService executor = Executors.newFixedThreadPool(5);
executor.submit(() -> {
System.out.println("Task executed by thread pool");
});
executor.shutdown();
ThreadPoolExecutor 自定义线程池参数。
ThreadPoolExecutor executor = new ThreadPoolExecutor(
2, 4, 60, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(10)
);
executor.execute(task);
线程中断处理
interrupt()方法
通过interrupt()请求中断线程,需检查中断状态。
Thread thread = new Thread(() -> {
while(!Thread.currentThread().isInterrupted()) {
// 执行任务
}
});
thread.start();
thread.interrupt();
线程局部变量
ThreadLocal类 为每个线程维护独立的变量副本。
ThreadLocal<String> threadLocal = ThreadLocal.withInitial(() -> "Initial");
threadLocal.set("Thread-specific value");
String value = threadLocal.get();






