您的位置:首页 > 编程语言 > Java开发

Concurrent Programming in Java - Single Threaded Execution

2016-09-16 13:01 447 查看

多线程设计模式 -- 独木桥模式

1.死锁的产生(就餐者同时拥有刀子和叉子时,可以就餐,否则谁也吃不到!)

package com.record.test.thread.SingleThreadedExecution.eatingQ;

public class Main {

public static void main(String[] args) {
Tool spoon = new Tool("Spoon");
Tool fork = new Tool("Fork");
new EaterThread("Alice", spoon, fork).start();
new EaterThread("Bobby", fork, spoon).start();
}

}

class EaterThread extends Thread{

private String name;
private Tool lefthand;
private Tool righthand;

public EaterThread(String name, Tool lefthand, Tool righthand) {
super();
this.name = name;
this.lefthand = lefthand;
this.righthand = righthand;
}

@Override
public void run() {
while (true) {
eat();
}
}

public void eat() {
synchronized (lefthand) {
System.out.println(name + " takes up " + lefthand + "(left).");
synchronized (righthand) {
System.out.println(name + " takes up " + righthand +" (right). ");
System.out.println(name + " is eating now, yaw yaw! ");
System.out.println(name + " puts down " + righthand + " (right). ");
}
System.out.println(name + " puts down " + lefthand + " (left). ");
}
}

}

class Tool{

private String name;

public Tool(String name) {
super();
this.name = name;
}

@Override
public String toString() {
return name + " ";
}

}

2.效果图

Bobby takes up Fork (left).
Alice takes up Spoon (left).

3.死锁的避免(修改就餐者拿刀叉的顺序,即可)

4.修改后的效果图

Alice takes up Spoon (left).
Alice takes up Fork  (right).
Alice is eating now, yaw yaw!
Alice puts down Fork  (right).
Alice puts down Spoon  (left).
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: