兄弟我改良了下你的代码可以更清晰的看到变化你那一下count就蹦到30000多了云里雾里的
package product_custom;
class Resource extends Thread
{
private String name;
private int count=0;
private boolean flag = false;
public synchronized void set(String name)
{
if (flag)
{
try
{ Resource.sleep(100);
wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
count++;
this.name = name;
System.out.println(Thread.currentThread().getName()+"....生产者生产"+this.name+count);
flag = true;
notify();
}
public synchronized void out()
{
if (!flag)
{
try
{
Resource.sleep(100);
wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+"........消费"+this.name+count);
flag = false;
notify();
}
}
//输入
class Producer implements Runnable
{
private Resource r;
Producer(Resource r)
{
this.r = r;
}
public void run()
{
while (true)
{
r.set("烤鸭");
}
}
}
//shuchu
class Consumer implements Runnable
{
private Resource r;
Consumer(Resource r)
{
this.r = r;
}
public void run()
{
while (true)
{
r.out();
}
}
}
class IntOutputTest
{
public static void main(String[] args)
{
Resource r = new Resource();
Producer pro = new Producer(r);
Consumer con = new Consumer(r);
Thread t1 = new Thread(pro,"第一个生产者 ");
Thread t2 = new Thread(pro,"第二个生产者");
Thread t3 = new Thread(con,"第一个消费者");
Thread t4 = new Thread(con,"第二个消费者");
t1.start();
t2.start();
t3.start();
t4.start();
}
} |