java线程死锁

来源:互联网 发布:jira mac 破解版下载 编辑:程序博客网 时间:2024/06/10 16:34

某个任务在等待另一个任务,而后者又在等待别的任务,这样一直等下去,

直到这个链条上的任务又在等待第一个任务释放锁,

这得到了一个任务之间相互等待的连续循环,

没有哪个线程能继续,这被称之为“死锁”。


死锁的4个条件

1.互斥条件。任务使用的资源中至少有一个是不能共享的。

2.至少有一个任务它必须持有一个资源且正在等待获取一个当前被别的任务持有的资源。

3.资源不能被任务抢占。

4.必须有循环等待。

public class Philosopher implements Runnable {public static class Chopstick {private boolean taken = false;private synchronized void taken() throws InterruptedException {while (taken) {wait();}taken = true;}private synchronized void drop() {taken = false;notifyAll();}}private Chopstick left;private Chopstick right;private final int id;private final int ponderFactor;private Random rand = 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) {TimeUnit.MILLISECONDS.sleep(rand.nextInt(ponderFactor * 200));}}@Overridepublic void run() {try {while (!Thread.interrupted()) {System.out.println(this + " " + "thinking");pause();System.out.println(this + " " + "grabbing right");right.taken();System.out.println(this + " " + "grabbing left");left.taken();System.out.println(this + " " + "eating");pause();right.drop();left.drop();}} catch (InterruptedException e) {System.out.println(this + " " + "interrupt");}}public String toString() {return "Philosopher " + id;}}

public class DeadLockingDiningPhilosophers {public static void main(String[] args) throws InterruptedException,IOException {int ponder = 5;if (args.length > 0) {ponder = Integer.parseInt(args[0]);}int size = 5;if (args.length > 1) {size = Integer.parseInt(args[1]);}ExecutorService exec = 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++) {exec.execute(new Philosopher(sticks[i], sticks[(i + 1) % size], i,ponder));}if (args.length == 3 && args[2].equals("timeout")) {TimeUnit.SECONDS.sleep(5);} else {System.out.println("Press 'Enter' to quit");System.in.read();}exec.shutdown();}}

5个哲学家围成一个圆,左手右手有一只筷子,只有当一个哲学家拥有左右2只筷子的时候才能吃饭

当ponder=0时,越容易发生死锁。

0 0