/*生产者,消费者*/
class SynchronizedE
{
public static void main(String[] args)
{
SyncStack stack = new SyncStack();
Runnable source = new Producer(stack);
Runnable sink = new Consumer(stack);
Thread t1 = new Thread(source);
Thread t2 = new Thread(sink);
t1.start();
t2.start();
System.out.println("Hello World!");
}
}
class Producer implements Runnable
{
SyncStack theStack;
public Producer(SyncStack s)
{
theStack = s;
}
public void run()
{
char c;
for (int i=0;i<6 ;i++ )
{
c = (char)(Math.random()*26+'A');
theStack.push(c);
System.out.print("生产者生产:"+c+",");
try
{
Thread.sleep((int)(Math.random()*100));
}
catch (InterruptedException e){}
}
}
}
class Consumer implements Runnable
{
SyncStack theStack;
public Consumer(SyncStack s)
{
theStack = s;
}
public void run()
{
char c;
for (int i=0;i<6 ;i++ )
{
c = theStack.pop();
System.out.print("消费者消费:"+c);
try
{
Thread.sleep((int)(Math.random()*1000));
}
catch (InterruptedException e){}
}
}
}
class SyncStack
{
private int index = 0;
private char buffer[] = new char[6];
public void push(char c)
{
while(index == buffer.length)
{
synchronized(this)
{
try
{
this.wait();
}
catch (InterruptedException e){}
}
}
this.notify();
buffer[index] = c;
index++;
}
public synchronized char pop()
{
while (index==0)
{
try
{
this.wait();
}
catch (InterruptedException e){}
}
this.notify();
index--;
return buffer[index];
}
}
为什么运行通不过啊???求解,哪里有问题??
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |