public class Product { private String lock; public Product(String lock) { this.lock = lock; } public void setValue() { try { synchronized (lock) { if(!ValueObject.value.equals("")){ lock.wait(); } String value=System.currentTimeMillis()+""; System.err.println("set"+"++++++++++++++++++++++"); ValueObject.value=value; Thread.sleep(1000); lock.notify(); } } catch (InterruptedException e) { e.printStackTrace(); } } } public class Consumer { private String lock; public Consumer(String lock) { this.lock = lock; } public void getValue(){ try { synchronized (lock) { if(ValueObject.value.equals("")){ lock.wait(); } System.err.println("get"+"---------------------------"); ValueObject.value = ""; lock.notify(); } } catch (InterruptedException e) { e.printStackTrace(); } } } public class ThreadP extends Thread { private Product product; public ThreadP(Product product) { this.product = product; } @Override public void run() { while (true) { product.setValue(); } } } public class ThreadC extends Thread{ private Consumer consumer; public ThreadC(Consumer consumer) { this.consumer = consumer; } @Override public void run() { while (true) { consumer.getValue(); } } } public class ValueObject { public static String value = ""; } public class Test { public static void main(String[] args) { String lock=new String(""); Product product = new Product(lock); Consumer consumer = new Consumer(lock); ThreadP p = new ThreadP(product); ThreadC c = new ThreadC(consumer); p.start(); c.start(); } }
输出就是set和get交替打印