线程中用while循环
import java.util.LinkedList;
public class Syn{
private LinkedList<Object> myList =new LinkedList<Object>();
private int MAX = 10;
public Syn(){}
public void start(){
new Producer().start();
new Consumer().start();
}
public static void main(String[] args){
Syn s1 = new Syn();
s1.start();
}
class Producer extends Thread{
public void run(){
for(int i=0;i<50;i++){
try{
sleep(10);
}catch(Exception e){
e.getMessage();
}
synchronized(myList){
try{
while(myList.size() == MAX){ //用while循环,不用if()
System.out.println("warning: it's full!");
myList.wait();
}
Object o = new Object();
if(myList.add(o)){
System.out.println("Producer: " + o);
myList.notify();
}
}catch(InterruptedException e){
System.out.println("producer is interrupted!");
}
}
}
}
}
class Consumer extends Thread{
public void run(){
for(int i=0;i<50;i++){
try{
sleep(100);
}catch(Exception e){
e.getMessage();
}
synchronized(myList){
try{
while(myList.size() == 0){ ////用while循环,不用if()
System.out.println("warning: it's empty!");
myList.wait();
}
Object o = myList.removeLast();
System.out.println("Consumer: " + o);
myList.notify();
}catch(InterruptedException ie){
System.out.println("consumer is interrupted!");
}
}
}
}
}
}
//rt,多线程的生产者消费者模式,一个生产者和一个消费者,帮解释下为何不用if,要用while(),没弄明白。
...全文
相关推荐
浅谈线程通信wait,notify作用
主要介绍了浅谈线程通信wait,notify作用,具有一定借鉴价值,需要的朋友可以参考下
工作中用到的各种java功能代码大全
工作中用到的各种java功能代码大全
python多线程实现同时执行两个while循环的操作
主要介绍了python多线程实现同时执行两个while循环的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
在LABVIEW中用While循环中实现累加的两种方法
用labview在While循环中实现累加的两种方法
python多线程实现for循环_Python多线程实现同时执行两个while循环
如果想同时执行两个while True循环,可以使用多线程threading来实现。完整代码#coding=gbkfrom time import sleep, ctimeimport threadingdef muisc(func):while True:print 'Start playing: %s! %s' %(func,ctime())sleep(2)def move(func):whi...


Java SE
