📄 numberpc.java
字号:
import javax.swing.JApplet;
public class NumberPC extends JApplet{
NumStore numStore=new NumStore(); //两个线程的共享对象
ProducerThread producerThd=new ProducerThread(); //生产者线程
ConsumerThread consumerThd=new ConsumerThread(); //消费者线程
public void start(){ //启动生产者和消费者线程
producerThd.start();
consumerThd.start();
}
public void stop(){ //停止生产者和消费者线程
if(producerThd!=null) producerThd=null;
if(consumerThd!=null) consumerThd=null;
}
class NumStore{
int numData;
boolean haveNum=false;
public synchronized void putNum(int n){ //放入数据的同步方法
while(haveNum==true){ //消费者线程还未取走数据,则等待.
try{
wait(); //进入睡眠,并释放管程
}catch(InterruptedException e){}
}
numData=n;
haveNum=true; //表示已生成新的数据
notify(); //唤醒正在等待的消费者线程取走数据
}
public synchronized int getNum(){ //提取数据的同步方法
while(haveNum==false){ //生产者还没有放入新的数据,则等待.
try{
wait(); //进入睡眠,并释放管程
}catch(InterruptedException e){}
}
haveNum=false; //表示数据已取走
notify(); //唤醒正在等待的生产者线程放入新数据
return numData;
}
}
class ProducerThread extends Thread{ //生产者线程
public void run(){
int i=0;
while(true){
numStore.putNum(i);
try{
Thread.sleep(10);
}catch(InterruptedException e){}
i++;
}
}
}
class ConsumerThread extends Thread{ //消费者线程
public void run(){
while(true){
try{
Thread.sleep(1);
}catch(InterruptedException e){}
System.out.println("消费者取出数据:"+numStore.getNum());
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -