首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

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

2013-01-26 
关于多线程中使用while做循环而不使用if的解释package com.thread.exampleimport java.util.LinkedListp

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

1 楼 cuisuqiang 5 小时前   没什么说的

热点排行