来源:java编程思想
是指两个或两个以上的进程在执行过程中,因争夺资源而造成的一种互相等待的现象,若无外力作用,它们都将无法推进下去。
产生死锁的四个必要条件:
(1) 互斥条件:一个资源每次只能被一个进程使用。
(2) 占有且等待:一个进程因请求资源而阻塞时,对已获得的资源保持不放。
(3)不可强行占有:进程已获得的资源,在末使用完之前,不能强行剥夺。
(4) 循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系。
筷子类(资源类)
package com.thread;
public class Chopstick {
private boolean taken=false;
public synchronized void take() throws InterruptedException{
while(taken==true){
wait();
}
taken=true;
}
public synchronized void drop(){
taken=false;
notifyAll();
}
}
哲学家类(线程类)
package com.thread;
import java.util.concurrent.TimeUnit;
public class Philosopher implements Runnable{
private Chopstick left;
private Chopstick right;
private int id;
public Philosopher(Chopstick left,Chopstick right, int id){
this.left=left;
this.right=right;
this.id=id;
}
public void run(){
try{
while(!Thread.interrupted()){
System.out.println(this+" thinking");
TimeUnit.MILLISECONDS.sleep(0);
left.take();
System.out.println(this+" get left");
right.take();
System.out.println(this+" get right");
System.out.println(this+" eating");
left.drop();
right.drop();
}
}catch(InterruptedException e){
System.out.println(this+" interrupted");
}
}
public String toString(){
return "Philosopher "+id;
}
}
死锁版本(每个哲学家都先取自己左边的筷子,后取自己右边的筷子,就有可能大家都拿到左筷子等待右筷子,造成循环等待)
package com.thread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class DeadLockingPhilosopher {
public static void main(String[] args) throws InterruptedException{
int size=10;
Chopstick[] chopsticks=new Chopstick[size];
for(int i=0;i<size;i++){
chopsticks[i]=new Chopstick();
}
ExecutorService exec=Executors.newCachedThreadPool();
for(int i=0;i<size;i++){
exec.execute(new Philosopher(chopsticks[i],chopsticks[(i+1)%size],i));
}
TimeUnit.SECONDS.sleep(3);
}
}
非死锁版本(破除循环等待,只要有一个哲学家先取右筷子,后取左筷子)
package com.thread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class NoDeadLockingPhilosopher {
public static void main(String[] args) throws InterruptedException{
int size=10;
Chopstick[] chopsticks=new Chopstick[size];
for(int i=0;i<size;i++){
chopsticks[i]=new Chopstick();
}
ExecutorService exec=Executors.newCachedThreadPool();
for(int i=0;i<size;i++){
if(i<size-1){
exec.execute(new Philosopher(chopsticks[i],chopsticks[i+1],i));
}else{
exec.execute(new Philosopher(chopsticks[0],chopsticks[i],i));
}
}
TimeUnit.SECONDS.sleep(3);
}
}