import java.util.*; public class Test { public static void main(String[] args){ MyStack<Character> stack = new MyStack<>(); for ( int i = 0 ; i < 3 ; ++i) { new Thread( new Producer(stack)).start();//参数为一个带有runnable接口改写了run方法的对象 } for ( int i = 0 ; i < 2 ; ++i) { new Thread( new Consumer(stack)).start(); } } } class MyStack<T> { private LinkedList<T> list; private int count; public MyStack() { list = new LinkedList<>(); count = 0 ; } public synchronized int getSize() { return count; } public synchronized void push(T ele) { while (count >= 200 ) { try { this .wait(); } catch (InterruptedException e) { e.printStackTrace(); } } list.offerLast(ele); count++; this .notifyAll(); } public synchronized T pull() { while (count <= 0 ) { try { this .wait(); } catch (InterruptedException e) { e.printStackTrace(); } } T res = list.pollLast(); count--; this .notifyAll(); return res; } // return null if stack is empty public synchronized T peek() { return list.peekLast(); } } class Producer implements Runnable { private MyStack<Character> stack; public Producer(MyStack<Character> stack) { this .stack = stack; } @Override public void run() { while ( true ) { try { Thread.sleep( 100 ); } catch (InterruptedException e) { e.printStackTrace(); } char c = generateChar(); stack.push(c); System.out.println( "Producer pushed: " + c + " " + stack.getSize()); } } private char generateChar() { return ( char )( new Random().nextInt( 26 ) + 'a' );//随机生成英文 } } class Consumer implements Runnable { private MyStack<Character> stack; public Consumer(MyStack<Character> stack) { this .stack = stack; } @Override public void run() { while ( true ) { try { Thread.sleep( 100 ); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println( "Consumer pulled: " + stack.pull() + " " + stack.getSize()); } } } |