使用Thread的wait和notify方法实现线程通信
2014-05-28 12:37
537 查看
package thread1; /** * 线程通信例子(基于线程wait,notify) * */ public class PC { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Q q = new Q(); new Producer(q); new Customer(q); //System.out.println("Press Control-C to stop."); } } /** * 阻塞队列 * */ class Q{ int n; boolean valueSet = false; @SuppressWarnings("static-access") synchronized int get(){ //值未设置好,循环等待 while(!valueSet){ try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //取值成功 System.out.println("Got:"+n); //将设置标志置为false valueSet = false; try { Thread.currentThread().sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } //通知设值线程 this.notify(); return n; } @SuppressWarnings("static-access") synchronized void put(int n){ //已经设置好了值,而且未被取走,循环等待 while(valueSet){ try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } this.n = n; //将设置标志设置为true valueSet = true; System.out.println("Put:"+n); try { Thread.currentThread().sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } //通知取值线程,可以取值 this.notify(); } } /** * 生产者 * */ class Producer implements Runnable{ Q q; public Producer(Q q){ this.q = q; new Thread(this,"Producer").start(); } @Override public void run() { // TODO Auto-generated method stub int i=0; while(true){ q.put(i++); } } } /** * 消费者 * */ class Customer implements Runnable{ Q q; public Customer(Q q){ this.q=q; new Thread(this,"Customer").start(); } @Override public void run() { // TODO Auto-generated method stub while(true){ q.get(); } } }
相关文章推荐
- Thread_wait、notify、notifyAll的使用方法
- Thread_wait、notify、notifyAll的使用方法
- Java中的Object的Wait() 和notify()方法使用时应注意的地方和Thread中的sleep()方法
- Java中的Object的Wait() 和notify()方法使用时应注意的地方和Thread中的sleep()方法
- Thread_wait、notify、notifyAll的使用方法
- Thread_wait、notify、notifyAll的使用方法
- Thread_wait、notify、notifyAll的使用方法
- Thread_wait、notify、notifyAll的使用方法
- Thread_wait、notify、notifyAll的使用方法
- 使用Object类中的wait()和notify()方法实现生产者和消费者模式
- java 的 Thread_wait、notify、notifyAll的使用方法
- thread的wait\notify实现线程通信
- Java中的Object的Wait() 和notify()方法使用时应注意的地方和Thread中的sleep()方法
- Thread_wait、notify、notifyAll的使用方法
- JavaSE第一百零四讲:哲学家就餐问题、死锁与使用wait及notify方法实现线程之间的相互通信
- Thread_wait、notify、notifyAll的使用方法
- Java:使用wait()与notify()实现线程间协作
- Silverlight 2.0使用Lock, Interlocked, EventWaitHandle, Monitor来实现线程同步//C#线程同步的几种方法
- Java:使用wait()与notify()实现线程间协作
- 使用Lock,wait/notify,Semaphore三种方式实现多线程通信