【发布时间】:2016-02-22 05:11:39
【问题描述】:
我已经为生产者消费者问题编写了代码,其中生产者生产了 3 次商品,然后只有消费者消费了 1 次。以下代码作为要求工作正常,但主线程不会停止。我不知道为什么它不会停止,我无法捕捉。能否请任何人查看下面的代码并更正它?
public class ProducerConsumerProblem
{
public static void main(String[] args)
{
ProducerConsumerStack st = new ProducerConsumerStack();
new ProducerThread(st);
new ConsumerThread(st);
}
}
class ProducerConsumerStack
{
int x;
boolean flag = false;
int producedCount = 0;
public synchronized void push(int x)
{
if (flag)
{ // flag==true
try
{
wait();
}
catch (Exception e)
{
System.out.println(e);
}
}
this.x = x;
System.out.println(x + " is produced..");
try
{
Thread.sleep(250);
}
catch (Exception e)
{
System.out.println(e);
}
this.producedCount++;
if (this.producedCount == 3)
{
this.producedCount = 0;
this.flag = true;
notifyAll();
}
}
synchronized public void pop()
{
if (!flag)
{ // flag==false
try
{
wait();
}
catch (Exception e)
{
System.out.println(e);
}
}
System.out.println(x + " is consumed.\n");
try
{
Thread.sleep(1500);
}
catch (Exception e)
{
System.out.println(e);
}
flag = false;
notify();
}
}
class ProducerThread implements Runnable
{
ProducerConsumerStack st = null;
ProducerThread(ProducerConsumerStack st)
{
this.st = st;
Thread t1 = new Thread(this);
t1.start();
}
public void run()
{
int a = 1;
for (int i = 0; i < 15; i++)
{
st.push(a++);
}
}
}
class ConsumerThread implements Runnable
{
ProducerConsumerStack st = null;
ConsumerThread(ProducerConsumerStack st)
{
this.st = st;
Thread t2 = new Thread(this);
t2.start();
}
public void run()
{
for (int i = 0; i < 15; i++)
{
st.pop();
}
}
}
【问题讨论】:
-
我不知道你为什么说,“主线程不会停止。”程序中的 main() 例程创建三个对象,然后退出。你真正想问的是什么?
-
P.S.,我在你的代码中发现了一个潜在的问题:它是对象的构造函数执行
new Thread(this).start();的地方。将this传递给构造函数中的另一个线程可能允许新线程访问处于未初始化/未完全初始化状态的对象。 -
@james large : 请运行相同的代码,然后查看主线程是否完成。它根本不会完成。
标签: java multithreading