importjava.util.*;
public classMyNumber {
privateListnum=newArrayList();
public static voidmain(String args[]) {
MyNumber m =newMyNumber();
newThread(newConsumer(m.getNum()),"消费者").start();
newThread(newProducer(m.getNum()),"生产者").start();
}
publicList getNum() {
returnnum;
}
}
classConsumerimplementsRunnable {
privateListnum=null;
private intcount=0;
publicConsumer(List list) {
this.num= list;
}
@Override
public voidrun() {
//TODO 自动生成的方法存根while(count<100) {
synchronized(num) {
String name = Thread.currentThread().getName();
if(num.size() ==0) {
try{
num.wait();
}catch(InterruptedException e) {
e.printStackTrace();
}
}else{
if(num.size() >0) {
num.remove(0);
num.notifyAll();
count++;
//System.out.println(name + "取出了数字" + num.get(0) + "!!!");System.out.println("现在还剩"+num.size() +"数字!");
}
}
}
}
}
}
classProducerimplementsRunnable {
privateListnum=null;
private intcount=0;
publicProducer(List list) {
this.num= list;
}
@Override
public voidrun() {
//TODO 自动生成的方法存根while(count<100) {
synchronized(num) {
String name = Thread.currentThread().getName();
if(num.size() >5) {
try{
num.wait();
}catch(InterruptedException e) {
e.printStackTrace();
}
}else{
String num1 =getNum();
num.add(num1);
num.notifyAll();
try{
Thread.sleep(100);
}catch(InterruptedException e) {
//TODO 自动生成的 catch 块e.printStackTrace();
}
count++;
System.out.println(name +"添加了一个数字!");
System.out.println("现在还有"+num.size() +"数字!");
}
}
}
}
private staticString getNum() {
String st;
Random ra =newRandom();
inta = ra.nextInt(9);
st = String.valueOf(a);
returnst;
}
}