多线程协同 |
锁死了,全部等待notifyAll()
package Practice;
import java.util.Random;
class Stage
{
Random rand=new Random();
private int size;
private int count;
public void setSize(int size){this.size=size;}
public void setCount(int count){this.count=count;}
public int getSize(){return size;}
public int getCount(){return count;}
public String toString(){return "仓库大小:"+size+"\t剩余:"+count+"。";}
public boolean flag=false;
public synchronized void push()
{
while(flag)
try{wait();}
catch(Exception e){}
int temp=rand.nextInt(size-count);
System.out.println(toString()+Thread.currentThread().getName()+",准备生产:"+temp);
count+=temp;
flag=true;
notifyAll();
}
public synchronized void pop()
{
while(!flag)
try{wait();}
catch(Exception e){}
int temp=rand.nextInt(count);
System.out.println(toString()+Thread.currentThread().getName()+",准备消费:"+temp);
count=count-temp;
flag=false;
notifyAll();
}
}
class Productor implements Runnable{
// TODO Auto-generated method stub
private Stage s;
Productor(Stage s){this.s=s;}
public void run() {
while(true)
s.push();
}
}
class Consummer implements Runnable{
private Stage s;
Consummer(Stage s){this.s=s;}
public void run() {
// TODO Auto-generated method stub
while(true)
s.pop();
}
}
public class MyThreadTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
;
Stage s=new Stage();
s.setSize(80);
s.setCount(10);
new Thread(new Productor(s) ).start();
new Thread(new Productor(s) ).start();
new Thread(new Consummer(s) ).start();
new Thread(new Consummer(s) ).start();
}
}//打印结果
/*仓库大小:80 剩余:69。Thread-1,准备生产:2
仓库大小:80 剩余:71。Thread-2,准备消费:51
仓库大小:80 剩余:20。Thread-1,准备生产:47
仓库大小:80 剩余:67。Thread-3,准备消费:49
仓库大小:80 剩余:18。Thread-0,准备生产:16
仓库大小:80 剩余:34。Thread-3,准备消费:30
仓库大小:80 剩余:4。Thread-1,准备生产:31
仓库大小:80 剩余:35。Thread-2,准备消费:14
仓库大小:80 剩余:21。Thread-1,准备生产:26
仓库大小:80 剩余:47。Thread-3,准备消费:34
.
.
.
*/多线程其他常见操作 |
黑马程序员——Java多线程基础知识2,布布扣,bubuko.com
原文地址:http://zhangwei9004.blog.51cto.com/8886503/1409757