多线程是 Java 的强大特性之一,它允许程序并发执行多个任务,提高资源利用率和响应能力。无论是 Web 服务、高性能计算、文件下载、图像处理,还是后台任务调度,多线程都是提升效率的利器。
本篇文章将深入介绍 Java 多线程编程,包括创建线程、同步控制、线程通信、线程池与实际案例。
Thread
类java复制编辑public class MyThread extends Thread {
public void run() {
System.out.println("线程运行:" + Thread.currentThread().getName());
}
public static void main(String[] args) {
new MyThread().start();
}
}
🖼️ 图示:MyThread
→ Thread
→ 执行 run()
方法
Runnable
接口java复制编辑public class RunnableDemo {
public static void main(String[] args) {
Runnable task = () -> System.out.println("Runnable 执行:" + Thread.currentThread().getName());
new Thread(task).start();
}
}
优点:支持多继承结构、代码更清晰。
Callable
和 Future
java复制编辑import java.util.concurrent.*;
public class CallableDemo {
public static void main(String[] args) throws Exception {
Callable<String> task = () -> "返回结果:" + Thread.currentThread().getName();
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> result = executor.submit(task);
System.out.println(result.get());
executor.shutdown();
}
}
线程状态包括:
🖼️ 图示:Java Thread 生命周期状态图(NEW → RUNNING → TERMINATED)
synchronized
关键字java复制编辑public synchronized void safeMethod() {
// 线程安全代码
}
或同步代码块:
java复制编辑synchronized (this) {
// 临界区
}
java复制编辑public class TicketSale {
private int tickets = 10;
public synchronized void sell(String name) {
if (tickets > 0) {
System.out.println(name + " 卖出一张票,剩余:" + --tickets);
}
}
public static void main(String[] args) {
TicketSale ts = new TicketSale();
Runnable task = () -> {
for (int i = 0; i < 5; i++) ts.sell(Thread.currentThread().getName());
};
new Thread(task, "窗口A").start();
new Thread(task, "窗口B").start();
}
}
java复制编辑class Box {
private int content;
private boolean empty = true;
public synchronized void put(int value) throws InterruptedException {
while (!empty) wait();
content = value;
empty = false;
System.out.println("放入: " + value);
notify();
}
public synchronized void get() throws InterruptedException {
while (empty) wait();
System.out.println("取出: " + content);
empty = true;
notify();
}
}
public class ProducerConsumer {
public static void main(String[] args) {
Box box = new Box();
new Thread(() -> {
for (int i = 1; i <= 5; i++) {
try { box.put(i); } catch (Exception e) {}
}
}, "生产者").start();
new Thread(() -> {
for (int i = 1; i <= 5; i++) {
try { box.get(); } catch (Exception e) {}
}
}, "消费者").start();
}
}
相比频繁创建销毁线程,使用线程池更加高效。
java复制编辑ExecutorService pool = Executors.newFixedThreadPool(3);
Runnable task = () -> System.out.println("执行:" + Thread.currentThread().getName());
for (int i = 0; i < 5; i++) pool.execute(task);
pool.shutdown();
java复制编辑ExecutorService pool = new ThreadPoolExecutor(
2, 5, 60, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(10),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy()
);
java复制编辑ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(() -> {
System.out.println("每隔2秒执行一次:" + System.currentTimeMillis());
}, 0, 2, TimeUnit.SECONDS);
🖼️ 图示:定时器执行周期结构图(初始延迟 → 周期性重复)
类别 | 常用类名 |
---|---|
并发集合 | ConcurrentHashMap, CopyOnWriteArrayList |
线程工具类 | CountDownLatch, CyclicBarrier, Semaphore |
原子类 | AtomicInteger, AtomicBoolean |
java复制编辑public class DownloadSimulator {
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(3);
for (int i = 1; i <= 5; i++) {
final int fileNum = i;
pool.submit(() -> {
System.out.println("开始下载文件" + fileNum);
try { Thread.sleep(2000); } catch (Exception e) {}
System.out.println("下载完成文件" + fileNum);
});
}
pool.shutdown();
}
}
内容 | 推荐工具 / 方法 |
---|---|
创建线程 | Runnable / Callable |
同步控制 | synchronized, Lock |
并发数据结构 | ConcurrentHashMap 等 |
执行管理 | ThreadPoolExecutor |
线程通信 | wait/notify,BlockingQueue |
定时任务 | ScheduledExecutorService |
ReentrantLock
精细控制线程锁行为
CompletableFuture
异步编程实践
ForkJoinPool
实现并行递归任务
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。