///////////////////////////////////////////////////////////
//
//threadk.java
//
//开发者:周维伟
///////////////////////////////////////////////////////////
//简介:
//java
程序,一个生产者消费者
问题的简单模拟
///////////////////////////////////////////////////////////
publicclassthreadk{
intbox=0;
publicsynchronizedvoidproduct(inti){
while(box==5){
try{
System.out.println("生产者"+i+"进入等候集");
wait();
System.out.println("生产者"+i+"离开等候集");
}catch(InterruptedExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
System.out.println("生产者"+i+"开始生产");
box++;
System.out.println("生产者"+i+"结束生产"+"产品数量为"+box);
notifyAll();//我认为在生产完后应该解开所有的锁,让所有人都能进入就绪态去自由竞争那个窗口。
//前面的while(box==*)循环保证了这个方法的正确性。
}
publicsynchronizedvoidconsume(inti){
while(box==0){
try{
System.out.println("消费者"+i+"进入等候集");
wait();
System.out.println("消费者"+i+"离开等候集");
}catch(InterruptedExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
System.out.println("消费者"+i+"开始消费");
box--;
System.out.println("消费者"+i+"结束消费"+"产品数量为"+box);
notifyAll();
}
publicstaticvoidmain(String[]args){
//TODOAuto-generatedmethodstub
finalthreadkop=newthreadk();
Threadtc1=newThread(newRunnable(){
@Override
publicvoidrun(){
//TODOAuto-generatedmethodstub
while(true){//这里设置一个循环函数代表该单位将不时地生产,并保证每次只有一个人进行。
op.product(1);
try{
Thread.sleep(500+(int)(Math.random()*4000));//进行随眠一个随机时间以保证模拟这样一个随机事件