1 /* 2 * 在编写代码之前一定要做好类的规划 3 */ 4 class Productor implements Runnable { 5 Cache c = null; 6 Productor(Cache c) { 7 this.c = c; 8 } 9 @Override 10 public void run() { 11 // TODO Auto-generated method stub 12 int i = 1; 13 while(true) { 14 if(i == 0) { 15 c.put("11", "AA"); 16 }else { 17 c.put("22", "BB"); 18 } 19 i = (i+1)%2; 20 } 21 } 22 23 } 24 25 class Customer implements Runnable { 26 Cache c = null; 27 Customer(Cache c) { 28 this.c = c; 29 } 30 @Override 31 public void run() { 32 // TODO Auto-generated method stub 33 while(true) { 34 c.get(); 35 } 36 } 37 38 } 39 /* 40 * 操作一个缓冲区,先检查再读写, 41 * wait():把线程退出CPU,让给其他线程使用 42 * notify():通知发出wait()的线程来运行 43 */ 44 class Cache { 45 private String name = null; 46 private String sex = null; 47 private boolean isFull = false; 48 public synchronized void put(String name,String sex) { 49 if(isFull) 50 try{wait();}catch (Exception e) {} 51 this.name = name; 52 this.sex = sex; 53 isFull = true; 54 notify(); 55 } 56 public synchronized void get() { 57 if(!isFull) 58 try{wait();}catch (Exception e) {} 59 System.out.print(name + "--");//在输出语句中不可以使用this关键字 60 System.out.println(sex); 61 isFull = false; 62 notify(); 63 } 64 } 65 66 public class ThreadConmunication { 67 public static void main(String[] args) { 68 Cache c = new Cache();//在这里定义一个Cache的对象,目的是让两个线程都使用相同的对象(缓冲区) 69 new Thread(new Productor(c)).start(); 70 new Thread(new Customer(c)).start(); 71 } 72 }