- package cn.thread;
- import java.util.concurrent.locks.Condition;
- import java.util.concurrent.locks.Lock;
- import java.util.concurrent.locks.ReentrantLock;
- class Res{
- public String name;
- public int count = 1;
- boolean flag = false;
- Lock lock = new ReentrantLock();
- Condition conIn = lock.newCondition();
- Condition conOut = lock.newCondition();
- public void in(String name){
- lock.lock();
- try{
- while(flag)
- try {
- conIn.await();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- this.name = name + count;
- System.out.println(Thread.currentThread().getName()+"生产..."+ this.name);
- count++;
- flag = true;
- conOut.signal();
-
- }finally{
- lock.unlock();
- }
- }
-
- public void out(){
- lock.lock();
- try{
- while(!flag)
- try {
- conOut.await();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- System.out.println(Thread.currentThread().getName()+"出售......"+this.name);
- flag = false;
- conIn.signal();
-
- }finally{
- lock.unlock();
- }
-
- }
- }
- class Producer implements Runnable{
- Res r;
- public Producer(Res r){
- this.r = r;
- }
- public void run(){
- while(true){
- r.in("CX-5-->");
- }
- }
- }
- class Consumer implements Runnable{
- Res r;
- public Consumer(Res r){
- this.r = r;
- }
- public void run(){
- while(true){
- r.out();
- }
- }
-
- }
- public class ProducerConsumer {
- public static void main(String[] args) {
- Res r = new Res();
- Producer p = new Producer(r);
- Consumer c = new Consumer(r);
- Thread t1 = new Thread(p);
- Thread t2 = new Thread(p);
- Thread t3 = new Thread(c);
- Thread t4 = new Thread(c);
- t1.start();
- t2.start();
- t3.start();
- t4.start();
- }
- }
复制代码 在while中的标记位flag是怎么判断的?
我的理解是:flag的默认是false的,这个时候没有东西在,这个时候生产东西,生产好了就false变ture,说明有东西了
然后到消费,while中的!flag是false,那这样不就是下面消费的代码执行不到了?这里我卡住了,求解答
|
|