public class DeadLockDemo {
public static void main(String[] args) {
Task task_1 = new Task(true);
Task task_2 = new Task(false);
Thread t1 = new Thread(task_1);
Thread t2 = new Thread(task_2);
t1.start();
t2.start();
}
}
class Task implements Runnable{//定义线程任务
private boolean flag;
public Task(boolean flag){
this.flag=flag;
}
public void run(){
if(flag){
while(true) {
synchronized (MyLock.lock_a) {//线程t1先获取a锁
System.out.println(Thread.currentThread().getName() + "...if...lock_a");
synchronized (MyLock.lock_b) {//线程t1再获取b锁
System.out.println(Thread.currentThread().getName() + "...if...lock_b");
}
}
}
}else{
while(true) {
synchronized (MyLock.lock_b) {//线程t2先获取b锁
System.out.println(Thread.currentThread().getName() + "...else...lock_b");
synchronized (MyLock.lock_a) {//线程t2再获取a锁
System.out.println(Thread.currentThread().getName() + "...else...lock_a");
}
}
}
}
}
}
class MyLock{
public static final Object lock_a = new Object();
public static final Object lock_b = new Object();
}
死锁实例
最新推荐文章于 2021-12-04 19:24:21 发布