java实现线程同步一个生产者和一个消费者
2015-03-04 18:21
525 查看
package test; import java.util.Scanner; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Test{ static Scanner sc = new Scanner(System.in); static String line; static class Food{ static int id = 0; private int mid = id++; public Food() { } @Override public String toString() { return "食物id="+mid; } } static Food f = null; static class Producer implements Runnable{ @Override public void run() { while(!Thread.interrupted()){ synchronized (this) {//等待过程,对应消费过程,所以应该上锁 while(f!=null){ try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } System.out.println("生产"); synchronized (c) { f = new Food(); c.notifyAll(); } } } } static class Comsumer implements Runnable{ @Override public void run() { while(!Thread.interrupted()){ synchronized (this) { while(f==null){ try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } System.out.println("消费"+f); synchronized (p) { f = null; p.notifyAll(); } } } } static Producer p = new Producer(); static Comsumer c = new Comsumer(); public static void main(String[] args) { ExecutorService exe = Executors.newCachedThreadPool(); exe.execute(p); exe.execute(c); } }
相关文章推荐
- 经典线程同步问题(生产者&消费者)--Java实现
- Java 线程同步问题 生产者-消费者 算法实现 -Java学习笔记(29)
- 【线程同步2】java实现生产者消费者问题$扩展,出现的问题,思考
- java实现的生产者和消费者问题-涉及线程同步与通信
- 经典线程同步问题(生产者&消费者)--Java实现
- Java 多线程学习之生产者消费者模型:一个较完善的实现
- 线程同步生产者和消费者c和java不同实现
- 经典线程同步问题(生产者&消费者)--Java实现
- 【线程同步】java实现生产者消费者问题与线程中的wait与notify总结
- 从java多线程实现“生产者-消费者”模型来谈谈操作系统中线程状态的转换及线程同步的总结
- 每天学习一算法系列(31)(实现一个队列,队列的应用场景为:一个生产者线程将int 类型的数入列,一个消费者线程将int 类型的数出列)
- 生产者消费者问题的java实现
- java生产者消费者问题(线程同步与线程等待的应用)
- 用java实现生产者和消费者问题
- java多线程总结六:经典生产者消费者问题实现
- java生产者消费者问题(线程同步与线程等待的应用)
- 用java实现的生产者与消费者多线程同步互斥模型
- 多个生产者-一个消费者-进程间同步的例子 - OutputDebugString的实现
- java生产者和消费者问题之售票实现方法
- Java线程间同步实现生产者-消费者模式