目录
简介
Java 线程是多任务处理的核心工具,可以有效提高应用程序的性能。通过合理使用线程,程序可以并发执行多个任务,充分利用多核处理器的能力。
Java 线程基础
线程的概念
线程是操作系统调度的最小单位,一个 Java 进程可以包含多个线程。每个线程共享相同的进程资源,如内存、文件句柄等。
创建线程的方式
Java 提供了多种创建线程的方法,主要有以下两种:
1. 继承 Thread
类
class MyThread extends Thread {
public void run() {
System.out.println("线程运行中:" + Thread.currentThread().getName());
}
}
public class ThreadExample {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
2. 实现 Runnable
接口
class MyRunnable implements Runnable {
public void run() {
System.out.println("线程运行中:" + Thread.currentThread().getName());
}
}
public class RunnableExample {
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start();
}
}
线程的常见使用方法
线程同步
多个线程访问共享资源时,可能会发生数据不一致的问题。Java 提供了 synchronized
关键字来实现线程同步。
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}
线程通信
线程之间可以使用 wait()
、notify()
和 notifyAll()
进行通信。
class SharedResource {
private boolean available = false;
public synchronized void produce() throws InterruptedException {
while (available) {
wait();
}
available = true;
System.out.println("生产者生产了一个项目");
notify();
}
public synchronized void consume() throws InterruptedException {
while (!available) {
wait();
}
available = false;
System.out.println("消费者消费了一个项目");
notify();
}
}
线程池
使用 ExecutorService
可以管理线程池,避免手动创建和销毁线程的开销。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolExample {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(3);
for (int i = 0; i < 5; i++) {
executor.execute(() -> System.out.println("任务执行:" + Thread.currentThread().getName()));
}
executor.shutdown();
}
}
线程的最佳实践
- 使用线程池管理线程:避免频繁创建销毁线程。
- 避免死锁:合理使用锁,避免循环依赖。
- 使用并发工具类:如
ConcurrentHashMap
,CountDownLatch
。 - 合理设置线程优先级:避免线程饥饿问题。
- 使用守护线程:在后台运行服务类任务。
小结
本文详细介绍了 Java 线程的基础知识、常见使用方法和最佳实践。线程是构建高效并发应用的关键,理解其工作原理并掌握正确的使用方法至关重要。