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);
}
}
作者: loading……99.9 时间: 2013-8-30 12:24
因为你的生产者线程只执行了一次,线程就执行完成了,消费者也是同样的道理。分别把你的生产者和消费者线程run方法中用一个while控制一下,具体部分代码如下:
生产者线程修改如下
public void run(){
while(true)
{
int c = (new Random()).nextInt(new Integer(9));
theStack.push(c);
System.out.println("生产者生产了一个数字"+c);
}
}
消费者线程修改如下:
public void run(){
while(true)
{
int i = theStack.pop();
System.out.println("消费者取出了一个数字"+i);
}
}作者: 嵿級↘莮紸角 时间: 2013-8-30 12:55
package com.qindazhong1;
import java.util.Random;
import java.util.Vector;
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);
}