JAVA生产者消费者问题(多线程)

JAVA生产者消费者问题(多线程)

源代码:

//java多线程模拟生产者消费者问题

//ProducerConsumer是主类,Producer生产者,Consumer消费者,Product产品 //Storage仓库

public class ProducerConsumer {

}

public static void main(String[] args) { Storage s = new Storage(); } Producer p = new Producer(s); Consumer c = new Consumer(s); Thread tp = new Thread(p);//创建一个线程tp; Thread tc = new Thread(c);//创建一个线程tc; tp.start();//启动线程; tc.start();//启动线程;

class Consumer implements Runnable {//消费者类继承Runnable接口;

Storage s;

}

class Producer implements Runnable {//生产者类继承Runnable接口;

Storage s ; public Producer(Storage s){ this.s = s; } public Consumer(Storage s){//构造方法; this.s = s; } public void run() { } for(int i=0; i<20; i++){ Product p = s.pop();//取出产品 } try { Thread.sleep((int)(Math.random()*1500));//随机休息0~1.5秒; } catch (InterruptedException e) { } e.printStackTrace();

JAVA生产者消费者问题(多线程)相关文档

最新文档

返回顶部