在項目中,經常用到一種設計模式----單例模式,下面舉一個小案例,說明線程安全的單例模式在多線程中的應用,以供學習參考:
和尚吃饅頭:
100個饅頭,30個和尚,每個和尚最少吃一個饅頭,最多不超過4個饅頭,保證上述條件的情況下,
盡快将饅頭吃了!
要求是嚴格單例模式實作籃子類(存放饅頭的容器)。
[java] view plain copy print ?
- <span style="font-size:18px;">package java.thread;
- public class MantouDemo {
- public static void main(String[] args) {
- for(int i = 0 ; i < Box.uneatedMonks ; i ++){
- new Monk("tom" + i).start();
- }
- }
- }
- //籃子
- class Box{
- private static Box instance = null ;
- private static Object lock = new Object();
- //饅頭總數
- private int COUNT = 100 ;
- //沒吃饅頭的和尚數量
- public static int uneatedMonks = 30 ;
- public static Box getInstance(){
- if(instance != null){
- return instance ;
- }
- synchronized (lock){
- if(instance == null){
- instance = new Box();
- }
- return instance ;
- }
- }
- private Box(){
- }
- //擷取饅頭
- public int getMantou(Monk monk){
- //1.是否還有可吃饅頭
- if(COUNT == 0){
- return 0 ;
- }
- //2.和尚是否吃飽了
- if(monk.getCount() == Monk.MAX){
- return 0 ;
- }
- //3.還有多餘的饅頭
- if(COUNT > uneatedMonks){
- int tmp = COUNT ;
- COUNT -- ;
- //和尚是否是第一次吃饅頭
- if(monk.getCount() == 0){
- uneatedMonks -- ;
- }
- return tmp ;
- }
- //沒有多餘的饅頭
- else{
- if(monk.getCount() == 0){
- int tmp = COUNT;
- COUNT--;
- uneatedMonks--;
- return tmp ;
- }
- }
- return 0 ;
- }
- }
- //和尚
- class Monk extends Thread{
- public static int MAX = 4 ;
- public static int MIN = 1 ;
- //和尚吃了饅頭的數量
- private int count = 0 ;
- public int getCount() {
- return count;
- }
- public void setCount(int count) {
- this.count = count;
- }
- private String monkName ;
- public Monk(String monkName) {
- this.monkName = monkName ;
- }
- public void run() {
- Box box = Box.getInstance();
- while(true){
- int mantouNo = box.getMantou(this) ;
- if(mantouNo != 0){
- count ++ ;
- }
- else{
- break ;
- }
- yield();
- }
- System.out.println(monkName + " : " + count );
- }
- }
- </span>