gpt4 book ai didi

Java 等待/通知全部

转载 作者:行者123 更新时间:2023-12-01 13:44:52 28 4
gpt4 key购买 nike

一个简单的线程程序,其中写入器将内容放入堆栈,读取器从堆栈中弹出。

java.util.Stack;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class MailBox
{
Stack<Integer> stack;

static int num;

public MailBox()
{
stack = new Stack<Integer>();

num = 1;
}
}

class Reader implements Runnable
{

MailBox box;

public Reader(MailBox box)
{
this.box = box;
}

public void run()
{
Thread.currentThread().setName("Reader " + MailBox.num++);

for(int i = 0; i < 5; ++i)
{
synchronized (box)
{
try {

box.wait();

if(!box.stack.empty() && !box.stack.isEmpty())
{
int data = box.stack.pop();

System.out.println(Thread.currentThread().getName() + " popped " + box.stack.pop());
}
else
{
System.out.println("Empty");
}

} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

try {
Thread.currentThread();
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}
}

class Writer implements Runnable
{
MailBox box;

public Writer(MailBox box)
{
this.box = box;
}

public void run()
{
int min = 1;
int max = 3;

Thread.currentThread().setName("Writer " + MailBox.num++);

for(int i = 0; i < 5; ++i)
{
synchronized(box)
{
int data = (int)Math.random() * max + min;

box.stack.push(data);

System.out.println(Thread.currentThread().getName() + " pushed " + data);

box.notifyAll();
}

try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}
}

public class Review
{

public static void main(String args[])
{
MailBox box = new MailBox();

Writer writer = new Writer(box);

Writer apprentice = new Writer(box);

Writer publisher = new Writer(box);

Reader reader = new Reader(box);

Reader busy_reader = new Reader(box);

Reader slow_reader = new Reader(box);

Reader fast_reader = new Reader(box);

Reader ugly_reader = new Reader(box);

ExecutorService executor = Executors.newCachedThreadPool();

executor.execute(writer);

executor.execute(apprentice);

executor.execute(publisher);

executor.execute(reader);

executor.execute(busy_reader);

executor.execute(slow_reader);

executor.execute(fast_reader);

executor.execute(ugly_reader);

executor.shutdown();

}

}

程序似乎工作正常,只是读者偶尔会弹出一个空堆栈,从而生成 StackEmptyExceptions。

我已针对此情况采取了保护措施,那么为什么会生成这些异常?

最佳答案

您弹出对象两次:

int data = box.stack.pop();
System.out.println(Thread.currentThread().getName() + " popped " + box.stack.pop());

正如您在 documentation of stack 中看到的那样,pop 获取并删除数据。

关于Java 等待/通知全部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20432617/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com