您的位置:首页 > 其它

多线程案例----严格单例模式----和尚吃馒头问题

2017-07-29 00:14 567 查看
在项目中,经常用到一种设计模式----单例模式,下面举一个小案例,说明线程安全的单例模式在多线程中的应用,以供学习参考:

    和尚吃馒头:

100个馒头,30个和尚,每个和尚最少吃一个馒头,最多不超过4个馒头,保证上述条件的情况下,
尽快将馒头吃了!

要求是严格单例模式实现篮子类(存放馒头的容器)。

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 );
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息