Java多线程同步:死锁示例
在Java多线程编程中,死锁是一种常见的并发问题。当两个或更多的线程相互等待对方释放资源时,就会发生死锁。
以下是一个简单的Java死锁示例:
// 创建两个互斥的资源
class Resource {
private boolean locked;
Resource() {
locked = false;
}
// 锁定资源,如果已被锁定则返回false
synchronized void lock() {
if (locked) {
System.out.println("Resource is already locked by another thread.");
return;
}
locked = true;
System.out.println("Resource " + this + " is locked by thread " + Thread.currentThread().getName());
}
// 解锁资源
synchronized void unlock() {
if (!locked) {
System.out.println("Resource is already unlocked by another thread.");
return;
}
locked = false;
System.out.println("Resource " + this + " is unlocked by thread " + Thread.currentThread().getName());
}
}
// 创建两个线程,分别尝试获取资源
class ThreadA extends Thread {
Resource resource;
ThreadA(Resource res) {
resource = res;
}
public void run() {
try {
System.out.println("Thread A starting to acquire resource " + resource);
resource.lock(); // 线程A尝试锁定资源
System.out.println("Thread A successfully acquired resource " + resource);
Thread.sleep(2000); // 模拟长时间操作,防止死锁的发生
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
try {
if (resource.isLocked()) { // 确认资源是否已被其他线程锁定
System.out.println("Thread A detected that resource " + resource + " is still locked by another thread.");
resource.unlock(); // 解锁资源,释放其他线程等待的锁
}
else {
System.out.println("Resource " + resource + " was already unlocked by another thread.");
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Thread A ending.");
}
}
class ThreadB extends Thread {
Resource resource;
ThreadB(Resource res) {
resource = res;
}
public void run() {
try {
System.out.println("Thread B starting to acquire resource " + resource);
resource.lock(); // 线程B尝试锁定资源
System.out.println("Thread B successfully acquired resource " + resource);
Thread.sleep(2000); // 模拟长时间操作,防止死锁的发生
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
try {
if (resource.isLocked()) { // 确认资源是否已被其他线程锁定
System.out.println("Thread B detected that resource " + resource + " is still locked by another thread.");
resource.unlock(); // 解锁资源,释放其他线程等待的锁
}
else {
System.out.println("Resource " + resource + " was already unlocked by another thread.");
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Thread B ending.");
}
}
// 创建两个互斥资源
Resource resource1 = new Resource();
Resource resource2 = new Resource();
// 启动两个线程,分别尝试获取资源
new ThreadA(resource1).start();
new ThreadB(resource2).start();
这个例子中,如果两个线程都试图获取resource1
和resource2
中的一个资源,就会发生死锁。为防止这种情况,通常会设置超时时间或者使用其他的同步机制。
还没有评论,来说两句吧...