本篇文章給大家帶來的內容是關於Java中消費者問題的程式碼分析,有一定的參考價值,有需要的朋友可以參考一下,希望對你有所協助。
1.資源
public class Resource { //當前資源的數量 int num = 0; //當前資源的上限 int size = 10; //消費資源 public synchronized void remove() { //如果num為0,沒有資源了,需要等待 while (num == 0) { try { System.out.println("消費者進入等待"); this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } //如果線程可以執行到這裡,說明資源裡有資源可以消費 num--; System.out.println("消費者線程為:" + Thread.currentThread().getName() + "--資源數量:" + num); this.notifyAll(); } //生產資源 public synchronized void put() { //如果資源滿了,就進入阻塞狀態 while (num == size) { try { System.out.println("生產者進入等待"); this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } num++; System.out.println("生產者線程為:" + Thread.currentThread().getName() + "--資源數量:" + num); this.notifyAll(); }}
2.消費者
public class Consumer implements Runnable { private Resource resource; public Consumer(Resource resource) { this.resource = resource; } @Override public void run() { while (true){ resource.remove(); } }}
3.生產者
public class Producer implements Runnable { private Resource resource; public Producer(Resource resource){ this.resource=resource; } @Override public void run() { while (true){ resource.put(); } }}
4.測試
public class TestConsumerAndProducer { public static void main(String[] args) { Resource resource = new Resource(); //生產線程 Producer p1 = new Producer(resource); //消費線程 Consumer c1 = new Consumer(resource); new Thread(p1).start(); new Thread(c1).start(); }}