本帖最后由 地狱天堂 于 2014-8-27 20:48 编辑
我写的代码,运行后先有消费,再有生产,哪出问题了?看了半天没找出来
- import java.util.concurrent.locks.Condition;
- import java.util.concurrent.locks.Lock;
- import java.util.concurrent.locks.ReentrantLock;
- public class TestEveryDay {
- public static void main(String[] args) {
- Res r=new Res();
- Producer pro=new Producer(r);
- Consume com=new Consume(r);
-
- new Thread(pro).start();
- new Thread(com).start();
- }
- }
- class Res{
- private String name;
- private int num=1;
- private boolean flag=false;
- private Lock lock=new ReentrantLock();
- private Condition condition_pro=lock.newCondition();
- private Condition condition_con=lock.newCondition();
-
- public void set(String name) throws InterruptedException{
- lock.lock();
- try {
- while(flag)
- condition_pro.await();
- this.name=name;
- System.out.println(Thread.currentThread().getName()+":生产者:"+name+num++);
- flag=true;
- condition_con.signal();
- } finally{
- lock.unlock();
- }
- }
- public void out() throws InterruptedException{
- lock.lock();
- try{
- while(!flag)
- condition_con.await();
- System.out.println(Thread.currentThread().getName()+":消费者...."+name+num);
- flag=false;
- condition_pro.signal();
- }finally{
- lock.unlock();
- }
- }
-
- }
- class Producer implements Runnable{
- private Res r;
- public Producer(Res r){
- this.r=r;
- }
- public void run() {
- while(true){
- try {
- r.set("商品");
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- }
- class Consume implements Runnable{
- private Res r;
- public Consume(Res r){
- this.r=r;
- }
- public void run() {
- while(true){
- try {
- r.out();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- }
复制代码 运行结果:
Thread-1:消费者....商品52831
Thread-0:生产者:商品52831
Thread-1:消费者....商品52832
Thread-0:生产者:商品52832
|
|