java线程如何应用
创建线程的两种方式
Java中创建线程主要有两种方式:继承Thread类或实现Runnable接口。
继承Thread类
通过继承Thread类并重写run()方法实现线程逻辑。
class MyThread extends Thread {
@Override
public void run() {
System.out.println("Thread running by extending Thread class");
}
}
// 启动线程
MyThread thread = new MyThread();
thread.start();
实现Runnable接口
更推荐的方式是实现Runnable接口,避免单继承限制。
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Thread running by implementing Runnable");
}
}
// 通过Thread类启动
Thread thread = new Thread(new MyRunnable());
thread.start();
线程池的使用
通过线程池管理线程资源,提高性能。Java提供ExecutorService框架实现线程池。
固定大小线程池
ExecutorService executor = Executors.newFixedThreadPool(5);
executor.submit(() -> {
System.out.println("Task executed by thread pool");
});
executor.shutdown(); // 关闭线程池
定时任务线程池
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(() -> {
System.out.println("Periodic task running");
}, 0, 1, TimeUnit.SECONDS); // 延迟0秒,每隔1秒执行
线程同步与锁
多线程共享资源时需同步以避免竞态条件。
synchronized关键字
修饰方法或代码块,确保同一时间只有一个线程访问。
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
}
ReentrantLock
更灵活的锁机制,需手动释放锁。
ReentrantLock lock = new ReentrantLock();
lock.lock();
try {
// 临界区代码
} finally {
lock.unlock();
}
线程间通信
通过wait()、notify()和notifyAll()实现线程协作。
生产者-消费者示例
class SharedBuffer {
private Queue<Integer> queue = new LinkedList<>();
private int capacity = 2;
public synchronized void produce(int item) throws InterruptedException {
while (queue.size() == capacity) {
wait(); // 缓冲区满时等待
}
queue.add(item);
notifyAll(); // 唤醒消费者线程
}
public synchronized int consume() throws InterruptedException {
while (queue.isEmpty()) {
wait(); // 缓冲区空时等待
}
int item = queue.poll();
notifyAll(); // 唤醒生产者线程
return item;
}
}
线程状态与生命周期
Java线程有以下状态:
NEW:新建未启动RUNNABLE:可运行或正在运行BLOCKED:等待监视器锁WAITING:无限期等待TIMED_WAITING:有限期等待TERMINATED:终止
通过Thread.getState()获取线程状态。
线程中断机制
通过interrupt()请求中断线程,需配合isInterrupted()检查。

Thread thread = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
System.out.println("Running...");
}
});
thread.start();
thread.interrupt(); // 发送中断信号
注意事项
- 避免直接调用
Thread.run(),应使用start()启动线程。 - 线程池需显式关闭,防止资源泄漏。
- 同步代码块应尽量缩小范围,减少性能影响。
- 谨慎使用
Thread.stop(),推荐通过中断机制安全终止线程。






