线程有关的基本程序,不知道哪里错了
消费者和生产者有关的问题,不知道哪里错了。一直都达不到wait和notify的效果。。
输出也是错的
public class ProducerConsumer {
public static void main(String args[]){
SyncStack ss = new SyncStack();
Producer p = new Producer(ss);
Consumer c = new Consumer(ss);
new Thread(p).start();
new Thread(c).start();
}
}
class Wotou{
int id;
Wotou(int id){
this.id = id;
}
public String toString()
{
return "Wotou" + id;
}
}
class SyncStack{
int index = 0;
Wotou[] arrWt = new Wotou[6];
public synchronized void push(Wotou wt){
while(arrWt.length == index){
try{
this.wait();
}
catch(InterruptedException e){
e.printStackTrace();
}
this.notifyAll();
arrWt[index] = wt;
index ++;
}
}
public synchronized Wotou pop(){
while(index == 0){
try{
this.wait();
}catch(Exception e){
e.printStackTrace();
}
}
this.notifyAll();
index --;
return arrWt[index];
}
}
class Producer implements Runnable{
SyncStack ss = null;
Producer(SyncStack ss){
this.ss = ss;
}
public void run(){
for(int i = 0 ; i<20 ; i++)
{
Wotou wt = new Wotou(i);
ss.push(wt);
try{
Thread.sleep(100);
}catch(Exception e){
e.printStackTrace();
}
System.out.println("生产了"+wt);
}
}
}
class Consumer implements Runnable{
SyncStack ss = null;
Consumer(SyncStack ss){
this.ss = ss;
}
public void run(){
for(int i = 0 ; i<20 ; i++){
Wotou wt = ss.pop();
System.out.println("消费了"+wt);
}
}
}
------最佳解决方案--------------------楼主下面代码有问题:
public synchronized void push(Wotou wt)
{
while(arrWt.length == index)
{
try
{
this.wait();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
this.notifyAll();//在while里面。
arrWt[index] = wt;
index ++;
}
}
当while(arrWt.length == index)不成立时,执行什么? 楼主的代码什么都不干,程序返回了。相当于 ss.push(wt);这句没有.
改正的方法是,把
this.notifyAll();
arrWt[index] = wt;
index ++;
放在while语句的外边。
如下:
public synchronized void push(Wotou wt)
{
while(arrWt.length == index)
{
try
{
this.wait();
}