关于多线程中使用while做循环而不使用if的解释

package com.thread.example;

import java.util.LinkedList;





public class Example10 {

	private LinkedList<Object> myList = new LinkedList<Object>();
	
	private int MAX = 10;
	
	public Example10() {
		super();
	}

	public void start(){
		new Producerder().start();
		new Consumereder().start();
	}



	class Producerder extends Thread {
		
		@Override
		public void run() {
			for (int i = 0; i < 15; i++) {
				try {
					this.sleep(1000);
				} catch (Exception e) {
					e.printStackTrace();
				}
				synchronized (myList) {
					try {
						while(myList.size() == MAX){
							System.out.println("warning: it's full!");
							myList.wait();
						}
						
						//*************把这一段注释掉********************
						Object o = new Object();
						if(myList.add(o)){
							System.out.println("Producer: " + o);
							myList.notify();
						}
						//*******************************
						//把上面注释掉后,启用下面一行后。你再在Consumereder中分别是用while和if看下输出结果
						//myList.notify();
					} catch (Exception e) {
						System.out.println("producer is interrupted!");
					}
				}
			}
		}
		
	}
	
	
	class Consumereder extends Thread {
		
		@Override
		public void run() {
			for (int i = 0; i < 15; i++) {
				try {
					this.sleep(100);
				} catch (Exception e) {
					e.printStackTrace();
				}
				
				synchronized (myList) {
					try {
						while(myList.size() == 0){
							System.out.println("warning: it's empty!");
							myList.wait();
						}
						System.out.println("oooooooooooooooooo");
						Object o = myList.removeLast();
						System.out.println("Consumereder" + o);
						myList.notify();
					} catch (Exception e) {
						   System.out.println("consumer is interrupted!");
					}
				}
			}
		}
		
	}

	
	public static void main(String[] args) {
		Example10 ex10 = new Example10();
		ex10.start();
	}
}

 注:根据代码中注释的操作运行一次,你就明白什么意思了;

        如果生产者没有生产,就调用唤醒(notify)。消费者的判断会出问题(如果使用if)

        这就是为什么使用while而不是if的原因

你可能感兴趣的:(thread,wait,notify,while和if)