并发-----死锁

形成死锁的四个条件

  • 互斥条件。任务使用的资源至少有一个是不能共享的。
  • 请求与保持条件。至少有一个任务必须持有一个资源且正在等待获取一个当前被别的任务持有的资源。
  • 不可剥夺条件。资源不能被任务抢占,任务必须把资源释放当做普通事件。
  • 循环等待条件。一个任务等待其他任务所持有的资源,后者又在等待另一个任务所持有的资源。
/**
 * Created by Panda on 2018/6/6.
 */
public class Chopstick {
    private boolean taken=false;
    public synchronized void take() throws InterruptedException{
        while (taken)
            wait();
        taken=true;
    }

    public synchronized void drop(){
        taken=false;
        notifyAll();
    }
}
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * Created by Panda on 2018/6/6.
 */
public class Philosopher implements Runnable {
    private Chopstick left;
    private Chopstick right;
    private final int id;
    private final int ponderFactor;
    private Random random = new Random(47);

    public Philosopher(Chopstick left, Chopstick right, int id, int ponderFactor) {
        this.left = left;
        this.right = right;
        this.id = id;
        this.ponderFactor = ponderFactor;
    }

    private void pause() throws InterruptedException{
        if(ponderFactor==0) return;
        TimeUnit.MILLISECONDS.sleep(random.nextInt(ponderFactor*250));
    }
    @Override
    public void run() {
        try{
            while (!Thread.interrupted()){
                System.out.println(this+" "+"thinking");
                pause();
                System.out.println(this+" "+"grabbing right");
                right.take();
                System.out.println(this+" "+"grabbing left");
                left.take();
                System.out.println(this+" "+"eating");
                pause();
                right.drop();
                left.drop();
            }
        }catch (InterruptedException e){
            System.out.println(this+" "+"exiting vis interrupt");
        }
    }
    public String toString(){return "Philosopher "+id;}
}

猜你喜欢

转载自blog.csdn.net/panda_____/article/details/80597071
今日推荐