Java多线程同步问题:死锁案例
死锁是多线程编程中的一种严重问题。当两个或更多的线程在执行过程中,因争夺资源而造成的一种互相等待的现象称为死锁。
下面是一个简单的死锁案例:
// 定义两个共享资源
class Resource {
private int count = 0;
// 让一个线程增加count,另一个线程减少count
public synchronized void increse() { count++; }
public synchronized void decrease() { count--; if(count < 0) throw new RuntimeException("Invalid state"); }
// 获取当前的count值,需要同步
public synchronized int getCount() { return count; }
}
// 定义两个线程,每个线程都需要资源
class WorkerThread implements Runnable {
private Resource resource;
public WorkerThread(Resource resource) { this.resource = resource; }
@Override
public void run() {
try {
// 线程A:增加count
while (true) {
if (resource.increase()) {
System.out.println("Thread A increased count to " + resource.getCount());
break;
} else {
System.out.println("Thread A couldn't increase count");
Thread.sleep(1000);
}
}
// 线程B:减少count
while (true) {
if (resource.decrease()) {
System.out.println("Thread B decreased count to " + resource.getCount());
break;
} else {
System.out.println("Thread B couldn't decrease count");
Thread.sleep(1000);
}
}
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
// 主程序,启动两个线程
public class Main {
public static void main(String[] args) {
Resource resource = new Resource();
Thread threadA = new Thread(new WorkerThread(resource)));
Thread threadB = new Thread(new WorkerThread(resource)));
// 启动线程
threadA.start();
threadB.start();
// 等待所有线程完成
try {
threadA.join();
threadB.join();
} catch (InterruptedException e) {
System.err.println(e.getMessage());
}
}
}
在这个案例中,线程A需要增加资源的count值,而线程B需要减少这个count值。但由于两个线程同时操作同一个资源,可能导致循环等待(死锁)的情况。
还没有评论,来说两句吧...