关于多线程中使用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的原因

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值