馒头问题
一共100个馒头,一个工人至多吃3个馒头
class ManTou
{
public static void main(String []args){
//创建篮子
Basket basket=new Basket();
for(int i=0;i<=40;i++){
new Worker("Work-"+i,basket).start();
}
}
}
//因为工人吃馒头,一起来吃所以要引发线程
class Worker extends Thread
{
private String name;
private static int MAX=3;//工人所吃馒头的最大数
private int count;
private Basket basket;
public Worker(String name,Basket basket){
this.name=name;
this.basket=basket;
}
public void run(){
while(true){
//1.判断是否已经吃饱了
if(count>=MAX){
return ;
}
//2.去取馒头
int no=basket.getMantou();//馒头剩余量
if(no==0){
return ;
}
//3.拿到了馒头
count++;
System.out.println(name+":"+no);
}
}
}
class Basket
{
private int count=100;
//同步方法,以当前对象作为锁旗标
public synchronized int getMantou(){//馒头一个个拿所以加锁
int temp=count;
count--;
return temp>0? temp:0;
}
}
蜜蜂和蜂蜜问题
一共100只蜜蜂,一个蜜蜂一次生产一个蜂蜜放到罐子里,罐子里的蜂蜜达到20时,熊就吃掉
class BeeDemo
{
public static void main(String []args){
Box box=new Box();
for(int i=1;i<=100;i++){
new Bee("Bee-"+i,box).start();
}
new Bear("x2",box).start();
new Bear("x1",box).start();
}
}
//蜜蜂
class Bee extends Thread
{
private String name;
private Box box;
public Bee(String name,Box box){
this.name=name;
this.box=box;
}
public void run(){
while(true){
int n=box.add();
System.out.println(name+"生产了蜂蜜1:box:"+n);
}
}
}
//熊
class Bear extends Thread
{
private String name;
private Box box;
public Bear(String name,Box box){
this.name=name;
this.box=box;
}
public void run(){
while(true){
box.remove();
System.out.println(name+"吃掉了蜂蜜");
}
}
}
//罐子
class Box
{
private int MAX=20;
private int count;
//添加蜂蜜
public synchronized int add(){
while(count>=MAX){
try{
this.notify();//notify()运行完之后再释放
this.wait();//wait()锁旗标立马释放
}catch(Exception e){e.printStackTrace();}
}
return count++;
}
//移除蜂蜜
public synchronized void remove(){
while(count<MAX){
try{
this.wait();
}
catch(Exception e){e.printStackTrace();}
}
count=0;
this.notify();//通知蜜蜂生产蜂蜜
}
}
//String name=Thread.currentThead().getName();得到当前线程名称
//防止死锁,给等待时间wait(100)或者notifyAll