本帖最后由 梁清平 于 2012-5-28 12:54 编辑
这个程序不能运行还有哪些问题啊?请高手指点。。
//生产者和消费者的示例
import java.util.concurrent.locks .*;
//主线程
public class ConsumerProducerDemo
{
public static void main(String[] args)
{
Products p = new Products();
new Thread(new Producer(p)).start();
new Thread(new Producer(p)).start();
new Thread(new Consumer(p)).start();
new Thread(new Consumer(p)).start();
}
}
//定义一个产品类
class Products
{
private ReentrantLock lock = new ReentrantLock();
Condition condition_pro = lock.newCondition();
Condition condition_con = lock.newCondition();
private String name;
private int count;
private boolean flag;
public void input(String name)
{
lock.lock();
try
{
while(flag)
{
try
{
condition_pro.await();
}
catch(InterruptedException e)
{
System.out.println("线程唤醒异常!");
}
}
this.name = name+"---:"+count++;
System.out.println(Thread.currentThread().getName()+"..."+this.name);
}
finally
{
lock.unlock();
}
flag = true;
condition_con.signal();
}
public void output()
{
lock.lock();
try
{
while(!flag)
try
{
condition_con.await();
}
catch(InterruptedException e)
{
System.out.println("线程唤醒异常!");
}
System.out.println(Thread.currentThread().getName()+"!!!!!!"+this.name);
}
finally
{
lock.unlock();
}
flag = false;
condition_pro.signal();
}
}
//定义两个线程类
class Producer implements Runnable
{
private Products p;
Producer(Products p)
{
this.p = p;
}
public void run()
{
while(true)
p.input("产品");
}
}
class Consumer implements Runnable
{
private Products p;
Consumer(Products p)
{
this.p = p;
}
public void run()
{
while(true)
p.output();
}
} |