多线程生产者消费者模式实现一对一交替打印

实现生产者/消费者模式:一对一交替打印

public class MyService {  
    private ReentrantLock lock= new ReentrantLock();  
    private Condition condition = lock.newCondition();  
    private boolean hasValue = false;  

    public void set() {  
        try{  
            lock.lock();  
            while (hasValue == true) {  
                condition.await();  
            }  
            System.out.println("----");  
            hasValue = true;  
            condition.signal();  
        } catch (InterruptedException e) {  
            e.printStackTrace();  
        } finally {  
            lock.unlock();  
        }  
    }  

    public void get() {  
        try {  
            lock.lock();  
            while (hasValue == false) {  
                condition.await();  
            }  
            System.out.println("****");  
            hasValue = false;  
            condition.signal();  
        } catch (InterruptedException e) {  
            e.printStackTrace();  
        } finally {  
            lock.unlock();  
        }  
    }  
}  
//两个线程
public class MyThread1 extends Thread {  
    private MyService service;  
    public MyThread1(MyService service) {  
        this.service = service;  
    }  
    @Override  
    public void run() {  
        for (int i=0; i<100; i++) {  
            service.set();  
        }  
    }  
}  

public class MyThread2 extends Thread{  
    private MyService service;  
    public MyThread2(MyService service) {  
        this.service = service;  
    }  
    @Override  
    public void run() {  
        for (int i=0; i<100; i++) {  
            service.get();  
        }  
    }  
} 

public class Run {  
    public static void main(String[] args) throws InterruptedException {  
        MyService service = new MyService();  
        MyThread1 a = new MyThread1(service);  
        a.start();  

        MyThread2 b = new MyThread2(service);  
        b.start();  

    }  
} 
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 创作都市 设计师:CSDN官方博客 返回首页