java多线程生产者消费者
2014-11-20 23:26
309 查看
//Java Thread producer customer class ThreadTest { public static void main(String[] args) { Q q=new Q(); Producer p=new Producer(q); Customer c=new Customer(q); Thread t0=new Thread(p); Thread t1=new Thread(c); t0.start(); t1.start(); for(int i=0;i<50;i++) { if(i==25) { p.stop(); c.stop(); } System.out.println(Thread.currentThread().getName()); } } } class Q { String name="empty"; String gender="empty"; boolean isEmpty=true; public synchronized void Put(String name,String gender) { if (!isEmpty) { try {wait();} catch (Exception ex) {} } this.name = name; try {Thread.sleep(1);} catch (Exception ex) {} this.gender = gender; isEmpty = false; notify(); } public synchronized void Get() { if(isEmpty) { try{wait();}catch(Exception ex){} } System.out.println("name:"+this.name+"__gender:"+this.gender); isEmpty=true; notify(); } } class Producer implements Runnable { Q q; boolean isStop=false; public void stop() { this.isStop=true; } public Producer(Q q) { this.q=q; } public void run() { int i = 0; while (!isStop) { if (i == 0) { q.Put("Tim", "male"); } else { q.Put("Lian", "female"); } i = (i + 1) % 2; } } } class Customer implements Runnable { Q q; boolean isStop=false; public void stop() { this.isStop=true; } public Customer(Q q) { this.q=q; } public void run() { while(!isStop) { q.Get(); } } }
View Code
相关文章推荐
- 由生产者/消费者问题看JAVA多线程
- java 用多线程实现多生产者和多消费者模式
- java多线程 生产者 消费者 问题 。。。
- java多线程总结六:经典生产者消费者问题实现
- java多线程总结六:经典生产者消费者问题实现
- 基于Java多线程机制的生产者-消费者模型模拟
- 用JAVA中的多线程示例生产者和消费者问题
- java多线程 生产者 消费者 问题 。。。
- java 多线程 生产者消费者
- JAVA多线程-生产者与消费者当线程多时发生死锁的解决方法
- java 多线程之 wait(),notify(),notifyAll()以及经典的生产者消费者模型
- 由生产者/消费者问题看JAVA多线程
- java多线程 消费者-生产者
- 回顾生产者/消费者问题下产生的java多线程(一)
- java多线程之生产者与消费者问题的简单模拟
- JAVA多线程实例(生产者与消费者问题)
- JAVA多线程模拟生产者与消费者_实例
- java多线程 消费者-生产者
- java多线程应用——生产者消费者
- 回顾生产者/消费者问题下产生的java多线程(二)