日期:2014-05-20 浏览次数:20787 次
class Storage { public int i = 0; } class Counter implements Runnable { private Storage storage; public Counter(Storage s) { storage = s; } public void run() { try { Thread.sleep(100); } catch(Exception e) { System.out.println(e); } for(int i = 0; i != 100; ++i) { synchronized(storage) { storage.i = i; System.out.println("counter: " +storage.i); storage.notify(); } } } } class Printer implements Runnable { private Storage storage; public Printer(Storage s) { storage = s; } public void run() { for(int i = 0; i != 100; ++i) { synchronized(storage) { try { storage.wait(); } catch(Exception e) { System.out.println(e); } System.out.println("printer: " +storage.i); } } } } public class TestThread { public static void main(String[] argv) { Storage s = new Storage(); Thread counter = new Thread(new Counter(s)); Thread printer = new Thread(new Printer(s)); printer.start(); counter.start(); } }
class Storage { public int i = 0; boolean isWaiting=false;//是否已在等待 } class Counter implements Runnable { private Storage storage; public Counter(Storage s) { storage = s; } public void run() { for(int i = 0; i != 100; ++i) { synchronized(storage) { //没有消费者等待,则不创建数据 if(!storage.isWaiting){ i--; continue; } storage.i=i; System.out.println("counter: " +storage.i); storage.notify();//通知消费者去取该数据 try { storage.wait();//等待消费者去使用数据 } catch (InterruptedException e) { e.printStackTrace(); } } } } } class Printer implements Runnable { private Storage storage; public Printer(Storage s) { storage = s; } public void run() { for(int i = 0; i != 100; ++i) { synchronized(storage) { try { storage.isWaiting=true;//必须要先等待 storage.wait();//等待生产者去创建数据 } catch(Exception e) { System.out.println(e); } System.out.println("printer: " +storage.i); storage.notify();//通知生产者去创建数据 } } } } public class TestThread { public static void main(String[] argv) { Storage s = new Storage(); Thread counter = new Thread(new Counter(s)); Thread printer = new Thread(new Printer(s)); printer.start(); counter.start(); } }