1:建立數據存儲對象代碼以下java
public class ValueObject { public static String value = ""; }
2:建立生產者代碼以下ide
public class Produce { private String lock; public Produce(String lock) { this.lock = lock; } public void setValue() { try { synchronized (this.lock) { while (!ValueObject.value.equals("")) { System.out.println("生產者" + Thread.currentThread().getName() + "WAITING 了 ☆"); this.lock.wait(); } System.out.println("生產者" + Thread.currentThread().getName() + "RUNNABLE了"); String value = System.currentTimeMillis() + "_" + System.nanoTime(); ValueObject.value = value; this.lock.notifyAll(); } } catch (InterruptedException e) { e.printStackTrace(); } } }
3:建立消費者代碼以下測試
public class Consumer { private String lock; public Consumer(String lock) { this.lock = lock; } public void getValue() { try { synchronized (this.lock) { while (ValueObject.value.equals("")) { System.out.println("消費者" + Thread.currentThread().getName() + "WAITING 了 △"); this.lock.wait(); } System.out.println("消費者" + Thread.currentThread().getName() + "RUNNABLE了"); ValueObject.value = ""; this.lock.notifyAll(); } } catch (InterruptedException e) { e.printStackTrace(); } } }
4:建立生產者線程代碼以下this
public class ThreadProduce extends Thread { private Produce produce; public ThreadProduce(Produce produce) { this.produce = produce; } @Override public void run() { while (true) { this.produce.setValue(); } } }
5:建立消費者線程代碼以下線程
public class ThreadConsumer extends Thread { private Consumer consumer; public ThreadConsumer(Consumer consumer) { this.consumer = consumer; } @Override public void run() { while (true) { this.consumer.getValue(); } } }
6:建立測試類代碼以下code
public class Test { public static void main(String[] args) throws InterruptedException { String lock = new String(); Produce produce = new Produce(lock); Consumer consumer = new Consumer(lock); ThreadProduce[] threadProduce = new ThreadProduce[2]; ThreadConsumer[] threadConsumer = new ThreadConsumer[2]; for (int i = 0; i < 2; i++) { threadProduce[i] = new ThreadProduce(produce); threadProduce[i].setName("生產者" + (i + 1)); threadConsumer[i] = new ThreadConsumer(consumer); threadConsumer[i].setName("消費者" + (i + 1)); threadProduce[i].start(); threadConsumer[i].start(); } Thread.sleep(5000); Thread[] threadArray = new Thread[Thread.currentThread().getThreadGroup().activeCount()]; Thread.currentThread().getThreadGroup().enumerate(threadArray); for (int i = 0; i < threadArray.length; i++) { System.out.println(threadArray[i].getName() + " " + threadArray[i].getState()); } } }