Java-經典消費者和生產者程式碼(面試題)
阿新 • • 發佈:2018-12-20
生產者程式碼
import java.util.Stack; public class Consumer extends Thread{ private Stack<Integer> stack; Consumer( Stack<Integer> stack){ super(); this.stack = stack; } @Override public void run() { synchronized (stack) { while(true){ if(!stack.empty()){ int pop = stack.pop(); System.out.println("pop"+pop); stack.notify(); }else{//等待 try { stack.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } }
消費者程式碼
package syncreadandwrite; import java.util.Stack; public class Producer extends Thread{ private Stack<Integer> stack; Producer( Stack<Integer> stack){ super(); this.stack = stack; } @Override public void run() { int i=0; synchronized (stack) { while(i<500){ if(stack.empty()){//為空,生產資料. stack.push(i); System.out.println("push"+i); i++; stack.notify(); }else{//不為空,等待資料被消費 try { stack.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } }
啟動類
package syncreadandwrite; import java.util.Stack; public class DemoClass { public static void main(String[] args) throws InterruptedException { Stack<Integer> stack = new Stack<Integer>(); Producer p = new Producer(stack); Consumer c = new Consumer(stack); p.start(); c.start(); } }
結果
push469
pop469
push470
pop470
push471
pop471
push472
pop472
push473
pop473
push474
pop474
push475
pop475
push476
pop476
push477
pop477
push478
pop478
push479
pop479
push480
pop480
push481
pop481
push482
pop482
push483
pop483
push484
pop484
push485
pop485
push486
pop486
push487
pop487
push488
pop488
push489
pop489
push490
pop490
push491
pop491
push492
pop492
push493
pop493
push494
pop494
push495
pop495
push496
pop496
push497
pop497
push498
pop498
push499
pop499
注意:notify()和wait()方法的配合使用,並且使用這兩個方法的時候必須獲取鎖物件