package com;
/*
* 生产类 */public class Producer implements Runnable { //开始操作数据存储类P P q = null; public Producer(P q){ this.q = q; }@Override
public void run() { int i = 0; while(true){ //编写往数据存储空间放入数据的代码 if( i == 0 ){ q.set("张三", "男"); }else{ q.set("李四", "女"); } i = (i+1)%2; } }}
package com;
/*
* 消费类 */public class Consumer implements Runnable { //开始操作数据存储类P P q = null; public Consumer(P q){ this.q = q; }@Override
public void run() { while(true){ //编写往数据存储空间取出数据的代码 while( true ){ q.get(); } } }}
package com;
/*
* 数据存储类 */public class P { //数据存储空间 private String name; private String sex; boolean bFull = false;//防止没有放入就不断读取或者没有取不断放入 //加入set和get方法进行数据同步以免资源共享产生差异 /* * wait(),notify(),notifyAll()方法只能在synchronized中调用 */ public synchronized void set(String name, String sex){ if( bFull ){//正在放入,先等等 try{ wait();//后来的线程要等待 }catch(InterruptedException e){ } } this.name = name; try{ Thread.sleep(10); }catch(Exception e){ System.out.println(e.getMessage()); } this.sex = sex; bFull = true; notify();//唤醒最先到达的线程 } public synchronized void get(){ if( !bFull ){//没有取,先等等 try{ wait();//后来的线程要等待 }catch(InterruptedException e){ } } System.out.println(this.name + "---->" + this.sex); bFull = false; notify();//唤醒最先到达的线程 }}
主类
package com;
public class ThreadCommunication {
/**
* 线程通讯 */ public static void main(String[] args) { P q = new P(); new Thread(new Producer(q)).start(); new Thread(new Consumer(q)).start(); }}