Java多线程详解
什么是多线程
多线程是指程序同时执行多个线程的能力,每个线程共享进程的内存空间,但拥有独立的执行栈和程序计数器。
创建线程的方式
继承Thread类
public class MyThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + ": " + i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.setName("线程A");
t2.setName("线程B");
t1.start();
t2.start();
}
}
实现Runnable接口
public class MyRunnable implements Runnable {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + ": " + i);
}
}
public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable(), "线程A");
Thread t2 = new Thread(new MyRunnable(), "线程B");
t1.start();
t2.start();
}
}
使用Callable和Future
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class MyCallable implements Callable<Integer> {
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
return sum;
}
public static void main(String[] args) {
FutureTask<Integer> futureTask = new FutureTask<>(new MyCallable());
Thread thread = new Thread(futureTask);
thread.start();
try {
Integer result = futureTask.get();
System.out.println("计算结果: " + result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
线程生命周期
public class ThreadLifecycleDemo {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
try {
System.out.println("线程运行中...");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
System.out.println("新建状态: " + thread.getState());
thread.start();
System.out.println("就绪/运行状态: " + thread.getState());
Thread.sleep(500);
System.out.println("睡眠中: " + thread.getState());
thread.join();
System.out.println("终止状态: " + thread.getState());
}
}
线程同步
synchronized关键字
public class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
public class SynchronizedDemo {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
Runnable task = () -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
};
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
Thread t3 = new Thread(task);
t1.start();
t2.start();
t3.start();
t1.join();
t2.join();
t3.join();
System.out.println("最终计数: " + counter.getCount());
}
}
同步代码块
public class SyncBlockDemo {
private int balance = 1000;
public void withdraw(int amount) {
synchronized (this) {
if (balance >= amount) {
balance -= amount;
System.out.println(Thread.currentThread().getName() +
"取款成功,余额: " + balance);
} else {
System.out.println(Thread.currentThread().getName() +
"余额不足");
}
}
}
public int getBalance() {
return balance;
}
}
线程通信
wait/notify
public class ProducerConsumerDemo {
private final int[] buffer = new int[5];
private int count = 0;
public synchronized void produce(int item) throws InterruptedException {
while (count == buffer.length) {
wait();
}
buffer[count++] = item;
System.out.println("生产: " + item);
notifyAll();
}
public synchronized int consume() throws InterruptedException {
while (count == 0) {
wait();
}
int item = buffer[--count];
System.out.println("消费: " + item);
notifyAll();
return item;
}
}
守护线程
public class DaemonThreadDemo {
public static void main(String[] args) {
Thread daemon = new Thread(() -> {
while (true) {
try {
Thread.sleep(1000);
System.out.println("守护线程运行中...");
} catch (InterruptedException e) {
break;
}
}
});
daemon.setDaemon(true);
daemon.start();
System.out.println("主线程运行5秒后退出");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("主线程退出,守护线程也会终止");
}
}
线程中断
public class InterruptDemo {
public static void main(String[] args) throws InterruptedException {
Thread worker = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
try {
System.out.println("工作中...");
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println("收到中断信号,准备退出");
break;
}
}
System.out.println("线程退出");
});
worker.start();
Thread.sleep(2000);
System.out.println("请求中断线程");
worker.interrupt();
}
}
多线程最佳实践
- 优先使用Runnable/Callable而非继承Thread
- 使用线程池管理线程资源
- 正确使用同步机制避免死锁
- 使用volatile保证可见性
- 合理设置线程优先级
总结
多线程是Java并发编程的基础。理解线程的创建、同步和通信机制,能帮助你构建高效、安全的多线程应用程序。