日期:2014-05-20 浏览次数:20783 次
public class ThreadCommunication_4 { public static void main(String[] args) { Q q= new Q(); new Thread(new Producer(q)).start(); new Thread(new Consumer(q)).start(); } } class Q { private String name = "张孝祥"; private String sex = "男"; boolean bFull=false; public synchronized void put(String name, String sex) { if(bFull) { try { wait(); } catch(Exception e) { System.out.println(e.getMessage()); } } 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(Exception e) { System.out.println(e.getMessage()); } } System.out.println(name+"----->"+sex); bFull=false; notify(); } } class Producer implements Runnable { Q q = null; public Producer(Q q) { this.q=q; } public void run() { int i = 0; while(true) { if(i == 0) { q.put("张孝祥","男"); } else { q.put("陈琼","女"); } i = (i+1)%2; } } } class Consumer implements Runnable { Q q =null; public Consumer(Q q) { this.q=q; } public void run() { q.get(); }
public void run() { q.get(); }