哲学家问题
程序员文章站
2022-07-04 22:12:05
...
//哲学家问题
//什么是死锁?
//比如两个相互占用对方所需的资源,但是都不释放自己的
//所以就形成了无限等待的现象
//死锁一旦产生没有外力帮助就永远存在,对程序产生严重影响
public class DeadLock extends Thread{
protected Object tool;
static Object fork1 = new Object();
static Object fork2 = new Object();
public DeadLock(Object obj){
this.tool = obj;
if(tool == fork1){
this.setName("哲学家A");
}
if(tool == fork2){
this.setName("哲学家B");
}
}
@Override
public void run(){
if(tool == fork1){
synchronized(fork1){
try{
Thread.sleep(500);
}catch(Exception e){
e.printStackTrace();
}
synchronized(fork2){
System.out.println("哲学家A开始吃饭");
}
}
}
if(tool == fork2){
synchronized(fork2){
try{
Thread.sleep(500);
}catch(Exception e){
e.printStackTrace();
}
synchronized(fork1){
System.out.println("哲学家B开始吃饭");
}
}
}
}
public static void main(String[] args) throws Exception{
DeadLock A = new DeadLock(fork1);
DeadLock B = new DeadLock(fork2);
A.start();
B.start();
Thread.sleep(1000);
}
}
上一篇: oracle中commit之后回滚
下一篇: 哲学家问题