- class Resource{
- private String name;
- private int count = 1;
- private boolean flag = false;
-
- public synchronized void set(String name) {
- while(flag){
- try {
- this.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- this.name = name+"..."+count++;
- System.out.println(Thread.currentThread().getName()+"...生产者.."+this.name);
- flag = true;
- this.notifyAll();
- }
-
- public synchronized void out(){
- while(!flag){ //当处于等待状态的线程被唤醒时,应该再进行一次标志的判断,故而将if更换为while
- try {
- this.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- System.out.println(Thread.currentThread().getName()+".....消费者...."+this.name);
- flag = false;
- this.notifyAll(); //因为在等待的线程池中,先进入线程池中的会先唤醒,所以需要用notifyAll唤醒所有的线程
- }
- }
- class Producer implements Runnable{
- private Resource res;
-
- public Producer(Resource res) {
- this.res = res;
- }
- public void run() {
- while(true){
- res.set("+商品+");
- }
- }
- }
- class Consumer implements Runnable{
- private Resource res;
-
- public Consumer(Resource res) {
- this.res = res;
- }
-
- public void run() {
- while(true){
- res.out();
- }
- }
- }
- public class ProducerConsumerDemo {
- public static void main(String[] args) {
- Resource r = new Resource();
- /*
- * 当开启的线程超过两个时,这段代码会出现问题
- *
- */
- //new Thread(new Producer(r)).start(); //代码优化的写法
- Producer pro = new Producer(r);
- Consumer con = new Consumer(r);
-
- Thread t1 = new Thread(pro);
- Thread t2 = new Thread(pro);
- Thread t3 = new Thread(con);
- Thread t4 = new Thread(con);
-
- t1.start();
- t2.start();
- t3.start();
- t4.start();
- }
- }
复制代码
在上边的代码中,类Resource里面有一个while循环,我不是很理解它是怎么结束这个循环的,求大神给指点一下 |
|