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).
相关文章推荐
- 《Concurrent Programming in Java: Design Principles and Patterns》Second Edition
- 说Hand-over-hand lock: 通读Concurrent Programming in Java: Design Principles and Patterns (1)
- [Concurrent Programming in Java]CookieJar Problem
- Java中的线程(八)- Single Threaded Execution模式
- 啃"创建线程"一章的疑难解析: 通读Concurrent Programming in Java: Design Principles and Patterns (2)
- Concurrent and Real-Time Programming in Java
- Concurrent Programming in Java(TM): Design Principles and Pattern
- JAVA多线程(三)模式-Single Threaded Execution
- JAVA并发设计模式学习笔记(二)—— Single Threaded Execution Pattern
- [Java 多线程] Concurrent Programming in Java BOOK
- Java2核心技术第七版的学习笔记(三) Fundamental Programming Structures in Java(Java语言的基础)(二)
- 处理教材:Controlling Execution of "Thinking in Java"
- Concurrent and Distributed Computing in Java
- Declarative Programming in Java
- Exception in thread "Thread-6" java.util.ConcurrentModificationException
- TSung, 单机用户提高用户的并发数(Improve maximum number of concurrent users in a single PC)
- Java2核心技术第七版的学习笔记(三) Fundamental Programming Structures in Java(Java语言的基础)(三)
- Sams Teach Yourself Programming with Java in 24 Hours (4th Edition)
- Programming a Spider in Java (翻译by:shuidao)
- 线程之旅--Single Threaded Execution Pattern