public class SynTest {
public static void main(String[] args){
SynStack stack = new SynStack();
Thread producer1 = new Thread(new Producer(stack));
Thread consummer1 = new Thread(new Consummer(stack));
producer1.start();
consummer1.start();
}
}
class SynStack {
private Vector<Integer> list = new Vector<Integer>();
public synchronized int pop(){
int c ;
while(list.size()==0){
try{
this.wait();
}catch(Exception e){}
}
c = list.remove(list.size()-1); //进行弹栈操作
return c ;
}
class Producer implements Runnable{
private SynStack theStack;
public Producer(SynStack s){
this.theStack = s ;
}
public void run(){
int c = (new Random()).nextInt(new Integer(9));
theStack.push(c);
System.out.println("生产者生产了一个数字"+c);
}
}
class Consummer implements Runnable {
private SynStack theStack = new SynStack();
public Consummer(SynStack s){
this.theStack = s ;
}
public void run(){
int i = theStack.pop();
System.out.println("消费者取出了一个数字"+i);
}
}
public class SynTest {
public static void main(String[] args){
SynStack stack = new SynStack();
Thread producer1 = new Thread(new Producer(stack));
Thread consummer1 = new Thread(new Consummer(stack));
producer1.start();
consummer1.start();
}
}
class SynStack {
private Vector<Integer> list = new Vector<Integer>();
public synchronized int pop(){
int c ;
while(list.size()==0){
try{
this.wait();
}catch(Exception e){}
}
c = list.remove(list.size()-1); //进行弹栈操作
return c ;
}
class Producer implements Runnable{
private SynStack theStack;
public Producer(SynStack s){
this.theStack = s ;
}
public void run(){
//在这里用while(true)实现无限循环
while(true) {
int c = (new Random()).nextInt(new Integer(9));
theStack.push(c);
System.out.println("生产者生产了一个数字"+c);
}
}
}
class Consummer implements Runnable {
private SynStack theStack = new SynStack();
public Consummer(SynStack s){
this.theStack = s ;
}
public void run(){
//在这里用while(true)实现无限循环
while(true) {
int i = theStack.pop();
System.out.println("消费者取出了一个数字"+i);
}