package org.yangzlgg.thread.lock;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class DeadLock {
static class Chopstick{
private boolean taken = false;
public synchronized void take() throws InterruptedException{
while(taken){
wait();
}
taken = true;
}
public synchronized void drop(){
taken = false;
notifyAll();
}
}
static class Philosopher implements Runnable{
private Chopstick left;
private Chopstick right;
private final int id;
private final int ponderFactor;
private Random rand = new Random(47);
private void pause() throws InterruptedException{
TimeUnit.MILLISECONDS.sleep(rand.nextInt(ponderFactor * 250));
}
public Philosopher(Chopstick left, Chopstick right, int id, int ponder){
this.left = left;
this.right = right;
this.id = id;
this.ponderFactor = ponder;
}
@Override
public void run() {
try{
while(!Thread.interrupted()){
//System.out.println(this+" thinking");
//pause();
right.take();
System.out.println(this+" grabbing right");
left.take();
System.out.println(this+" grabbing left");
//System.out.println(this+" eating");
//pause();
right.drop();
left.drop();
Thread.yield();
}
}catch(InterruptedException e){
System.out.println(this +" "+"exiting via interrupt");
}
}
@Override
public String toString() {
return "#"+this.id;
}
}
static class Deadlock{
public static void main(String[] args) {
int ponder = 1;
int size = 5;
ExecutorService executorService = Executors.newCachedThreadPool();
Chopstick[] sticks = new Chopstick[size];
for (int i = 0; i < size; i++) {
sticks[i] = new Chopstick();
}
for (int i = 0; i < size; i++) {
if(i < size-1){
executorService.execute(new Philosopher(sticks[i], sticks[i+1], i, ponder));
}else{
executorService.execute(new Philosopher(sticks[0], sticks[i], i, ponder));
}
}
executorService.shutdown();
}
}
}
环形死锁
最新推荐文章于 2022-05-07 17:35:46 发布