理解并避免Java并发问题示例
Java并发问题是多线程编程中常见的问题,包括死锁、活锁、饥饿等问题。以下是一些理解并避免这些问题的示例:
- 死锁:多个线程等待对方释放资源导致无法继续执行。例如:
// 线程1拥有资源A
Thread t1 = new Thread(() -> {
// 线程2等待资源A
t2.join();
System.out.println("t1 finished");
});
// 线程2拥有资源B
Thread t2 = new Thread(() -> {
// 线程1等待资源B
if (resourceBAvailable(t1)) {
t1.notifyAll();
System.out.println("t2 notified t1");
} else {
System.out.println("No resource B available for t1 to continue");
}
});
// 创建资源B的模拟方法
boolean resourceBAvailable(Thread t) {
if (t == null || !t.isAlive()) {
return false;
}
// 模拟资源B需要一段时间才能准备
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
return true;
}
// 启动线程并等待完成
t1.start();
t2.start();
// 等待所有线程完成
while (Thread.activeCount() > 1) {
try {
// 如果某个线程还在运行,那么等待
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("All threads finished");
活锁:两个或多个线程在没有外部因素干预的情况下陷入相互等待对方释放资源的循环。解决办法包括超时机制、随机重试等。
饥饿:一个线程长时间得不到CPU执行,从而无法进行正常的工作。可以通过合理分配资源、优先级调度等方式避免。
理解和避免Java并发问题需要对多线程编程、同步原语(如synchronized关键字)、线程池和并发工具包有深入理解。
还没有评论,来说两句吧...