本帖最后由 月生春 于 2014-1-16 23:50 编辑
你在资源中没有设定资源的多少啊,那样肯定会一直运行下去,比如毕老师买票的例子,卖一百张票,卖掉一张就少一张,最后全部卖完!
我将代码改动一下,定义 count为100;
然后资源被占用时count就减减
class ZiYuan
{
private String name;
private int count=100;
//定义标记
private boolean flag;
//提供给商品赋值的方法
public synchronized void set(String name)
{
if(flag)//判断标记为true,执行wait等待,为false,就生产
{
try
{
wait();
}
catch (InterruptedException e)
{
}
}
this.name=name+"--"+count;
count--;
System.out.println(Thread.currentThread().getName()+"生产"+this.name);
//生产完毕,将标记改为true
flag=true;
//唤醒消费者
notify();
}
//提供获取商品的方法
public synchronized void get()
{
if(!flag)
{
try
{
wait();
}
catch (InterruptedException e)
{
}
}
System.out.println(Thread.currentThread().getName()+"消费"+this.name);
//消费完毕,将标记改为false
flag=false;
//唤醒生产者
notify();
}
}
class ShengChanZhe implements Runnable
{
private ZiYuan z;
public ShengChanZhe(ZiYuan z)
{
this.z=z;
}
public void run()
{
z.set("面包");
}
}
class XiaoFeiZhe implements Runnable
{
private ZiYuan z;
public XiaoFeiZhe(ZiYuan z)
{
this.z=z;
}
public void run()
{
z.get();
}
}
class MyTest3
{
public static void main(String[] args)
{
//创建资源
ZiYuan z=new ZiYuan();
//创建两个任务
ShengChanZhe s=new ShengChanZhe(z);
XiaoFeiZhe x=new XiaoFeiZhe(z);
//创建线程
Thread t1=new Thread(s);
Thread t2=new Thread(x);
t1.start();
t2.start();
}
}
|