- public class Day12Test2 {
- public static void main(String[] args) {
- Resouce r = new Resouce();
- new Thread(new Producer(r)).start();
- new Thread(new Producer(r)).start();
- new Thread(new Consumer(r)).start();
- new Thread(new Consumer(r)).start();
- }
- }
- class Resouce{
-
- private String name;
- private int count = 1;
- private boolean flag = false;
- private ReentrantLock 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_con.await();
- this.name = name + count++;
- System.out.println(Thread.currentThread().getName()+"...生产者......"+this.name);
- flag = true;
- condition_pro.signal();
- }
- finally{
- lock.unlock();
- }
-
- }
- public void out() throws InterruptedException{
- lock.lock();
- try{
- while(!flag)
- condition_pro.await();
- System.out.println(Thread.currentThread().getName()+"+消费者+"+this.name);
- flag = false;
- condition_con.signal();
- }
- finally{
- lock.unlock();
- }
- }
- }
- class Producer implements Runnable{
- private Resouce r;
- Producer(Resouce r){
- this.r = r;
- }
- public void run(){
- while(true){
- try {
- r.set("汉堡");
- } catch (InterruptedException e) {
- }
- }
- }
- }
- class Consumer implements Runnable{
- private Resouce r;
- Consumer(Resouce r){
- this.r = r;
- }
- public void run(){
- while(true){
- try {
- r.out();
- } catch (InterruptedException e) {
- }
- }
- }
- }
复制代码 |
|