package thread;
import java.util.Random;
/**
* 生产消费者模式,管程法
*
* @author Administrator
*
*/
public class TestStackThread {
public static void main(String[] args) {
TestStack testStack = new TestStack();
new PushChar(testStack).start();
;
new PopChar(testStack).start();
}
}
class PushChar extends Thread {
private TestStack stack;
public PushChar(TestStack stack) {
this.stack = stack;
}
public void run() {
Random random = new Random();
for (int i = 0; i < 1000; i++) {
stack.push((char) (random.nextInt(26) + 65));
}
}
}
class PopChar extends Thread {
private TestStack stack;
public PopChar(TestStack stack) {
this.stack = stack;
}
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println("出栈" + stack.pop());
}
}
}
class TestStack {
private char[] character = new char[10];
private int index = 0;
public synchronized void push(char c) {
// 栈满则等待数据出栈
while (index == character.length) {
try {
System.out.println("栈满,等待数据出栈……");
wait();// 线程阻塞,等待数据出栈后唤醒
} catch (InterruptedException e) {
}
}
System.out.println("入栈" + c);
character[index] = c;
index++;
notifyAll();// 释放对象锁,通知正在等待的线程重新占有
}
public synchronized char pop() {
while (index == 0) {
try {
System.out.println("栈空,等待数据入栈……");
wait();
} catch (InterruptedException e) {
}
}
index--;
char c = character[index];
notifyAll();
return c;
}
}