在一个多线程得环境当中,A线程拿了a资源再等待b资源,B线程拿到了b的资源,正在等待获取a资源。但是要求a和b资源均为共享资源,若不是共享资源,则不存在线程同步问题。
public class DeadLock {
static class MyThread extends Thread {
private int id;
public static Object resourceA = new Object();
public static Object resourceB = new Object();
public MyThread (int id){
this.id=id;
}
@Override
public void run() {
if(id==1){
synchronized (resourceA){
System.out.println("我的id="+this.id+",我已经拿到resourceA了,即将请求resouceB!");
try{
Thread.sleep(2000);
}catch (InterruptedException e){
e.printStackTrace();
}
synchronized (resourceB){
System.out.println("我的id="+this.id+",我已经拿到resourceB了,即将完成任务了!");
}
}
}else if(id==2){
synchronized (resourceB){
System.out.println("我的id="+this.id+",我已经拿到resourceB了,即将请求resourceA");
try{
Thread.sleep(2000);
}catch (InterruptedException e){
e.printStackTrace();
}
synchronized (resourceB){
System.out.println("我的id="+this.id+"我已经拿到resourceA了,即将完成任务!");
}
}
}
}
}
public static void main(String[] args) {
Thread t1=new MyThread(1);
Thread t2=new MyThread(2);
t1.start();
t2.start();
System.out.println("done!");
}
}