哲学家问题示例

2017-01-10  本文已影响0人  恶魔幻心

解决方法:无锁函数或者重入锁的中断或限时等待

public classSimpleThreadextendsThread{

staticObjecto1=newObject();

staticObjecto2=newObject();

inta;

publicSimpleThread(inti) {

a= i;

}

@Override

public voidrun() {

if(a==1){

synchronized(o1){

try{

Thread.sleep(500);

}catch(InterruptedException e) {

e.printStackTrace();

}

synchronized(o2){

System.out.println("哲学家A开始用餐;");

}

}

}else{

synchronized(o2){

try{

Thread.sleep(500);

}catch(InterruptedException e) {

e.printStackTrace();

}

synchronized(o1){

System.out.println("哲学家B开始用餐;");

}

}

}

}

public static voidmain(String[] args)throwsException{

SimpleThread d1 =newSimpleThread(1);

SimpleThread d2 =newSimpleThread(2);

d1.start();

d2.start();

Thread.sleep(1000);

}

}

上一篇下一篇

猜你喜欢

热点阅读