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(),没弄明白。
while(myList.size() == 0){ ////用while循环,不用if()
System.out.println("warning: it's empty!");
myList.wait();
}
和while(true){ ////用while循环,不用if()
if(myList.size() == 0){
System.out.println("warning: it's empty!");
myList.wait();}
}
有什么区别?
多用户
比如说,某个用户第一次得到锁时list为空,他wait,下次被唤醒时,list可能还是空的。因为有肯能其他用户购买了产品清空了表。如果用if他将不再判断list是否为空,直接继续,引起错误
但如果用while则每次被唤醒时都先检查list是否为空再继续生产基本是一个道理
不过用while更符合逻辑,才是纯粹的线程安全
当然有区别 if只有一次 while可以不止一次
myList.wait();这里wait后,线程等在这里
等到别个线程nofity后
继续执行,这时是有必要再判断myList.size()的大小的
简单地,满了的水桶不能再装水进去了
第二个使用while也是等到linckenlist为空的时候无限循环打印"warning: it's empty!而if不能实现循环。