numberpc2.java

来自「学习Java的一些基本课件和源代码 对于初学者很有帮助的」· Java 代码 · 共 48 行

JAVA
48
字号
import javax.swing.JApplet;
public class NumberPC2 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;
		public  synchronized void putNum(int n){  //放入数据
			numData=n;
			}
		public synchronized int getNum(){  //提取数据
			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());
			}
		}
	}
}				
/*<applet code=NumberPC2.class   width=200 height=200>
      </applet>*/

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?