线程同步问题
import java.util.*;class Store{
private int seq;
private boolean available=false;
public synchronized int get(){
while(available==false){
try{
wait();
}
catch(InterruptedException e){
}
}
available=false;
notify();
return seq;
}
public synchronized void put(int value){
while(available==true){
try{
wait();
}
catch(InterruptedException e){
}
}
seq=value;
available=true;
notify();
}
}
class Producer extends Thread{
private Store store;
private int num;
public Producer(Store s,int num){
store=s;
this.num=num;
}
public void run(){
for(int i=0;i<10;++i){
store.put(i);
System.out.println("Producer #"+this.num+"put:"+i);
try{
sleep((int)(Math.random()*1000));
}
catch(InterruptedException e){
}
}
}
}
class Consumer extends Thread{
private Store store;
private int num;
public Consumer(Store s,int num){
store=s;
this.num=num;
}
public void run(){
int value=0;
for(int i=0;i<10;++i){
value=store.get();
System.out.println("Consumer #"+this.num+"get:"+value);
}
}
}
class MyPrCon {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Store s=new Store();
Producer p=new Producer(s,2);
Consumer c=new Consumer(s,2);
p.start();
c.start();
}
}
输出结果是
Producer #2put:0
Consumer #2get:0
Consumer #2get:1
Producer #2put:1
Consumer #2get:2
Producer #2put:2
Consumer #2get:3
Producer #2put:3
Consumer #2get:4
Producer #2put:4
Producer #2put:5
Consumer #2get:5
Consumer #2get:6
Producer #2put:6
Consumer #2get:7
Producer #2put:7
Consumer #2get:8
Producer #2put:8
Consumer #2get:9
Producer #2put:9
为什么会这样呢,本来是要一个输出Producer,一个输出Consumer的,却出现输出两个Consumer的状况?