本帖最后由 wangaz 于 2015-6-1 14:00 编辑
记录一下学习过程中的点滴~
class ProducerConsumerDemo
{
public static void main(String[] args)
{
Resource res = new Resource();
Producer pro = new Producer(res);
Consumer con = new Consumer(res);
Thread d1 = new Thread(pro);
Thread d2 = new Thread(pro);
Thread d3 = new Thread(con);
Thread d4 = new Thread(con);
d1.start();
d2.start();
d3.start();
d4.start();
}
}
/*
resource
*/
class Resource
{
private String name;
private int count = 1;
private boolean flag = false;
public synchronized void set(String name)
{
while(flag)
try{this.wait();} catch(Exception e){}
this.name = name + "---" + count++;
System.out.println(Thread.currentThread().getName() + "production" + this.name);
this.flag = true;
this.notifyAll();
}
public synchronized void out()
{
while(!flag)
try{this.wait();} catch(Exception e){}
System.out.println(Thread.currentThread().getName() + "----consumption----" + this.name);
this.flag = false;
this.notifyAll();
}
}
/*
production
*/
class Producer implements Runnable
{
private Resource res;
Producer(Resource res)
{
this.res = res;
}
public void run()
{
while(true)
{
res.set("+haha+");
}
}
}
/*
consumer
*/
class Consumer implements Runnable
{
private Resource res;
Consumer(Resource res)
{
this.res = res;
}
public void run()
{
while(true)
{
res.out();
}
}
}
|
|