Tag: notify

生产者 – Java中的消费者multithreading

我想在Java中使用multithreading等待和通知方法编写程序。 该程序有一个堆栈(max-length = 5)。 生产者永远生成数字并将其放入堆栈中,消费者从堆栈中选择它。 当堆栈已满时,生产者必须等待,当堆栈为空时,消费者必须等待。 问题是它只运行一次,我的意思是一旦它产生5个数字就会停止,但是我将run方法放入while(true)块以运行不间断但它没有。 这是我到目前为止所尝试的。 制片人类: package trail; import java.util.Random; import java.util.Stack; public class Thread1 implements Runnable { int result; Random rand = new Random(); Stack A = new Stack(); public Thread1(Stack A) { this.A = A; } public synchronized void produce() { while (A.size() >= 5) { System.out.println(“List is Full”); try […]

谁和什么时候调用thread.join()时通知thread.wait()?

thread.join()将调用thread.wait() ,但是谁和何时通知(使用thread.notify()或notifyAll() ) thread.wait() ? 我们知道,线程连接将等待线程完成,但是谁调用了通知呢?

在Consumer和Producer Threads中等待并通知

刚开始学习multithreading。 我有多个线程的5个生产者和2个消费者。 基本上这个程序会在队列中添加100个项目。 当队列大小为100时,生产者将停止添加。我希望消费者在消费者从队列中删除所有项目时通知生产者,以便生产者可以再次开始添加。 目前生产者将等待,但永远不会得到消费者的通知。 制片人: public class Producer implements Runnable { private BlockingQueue sharedQueue; private final int queueSize; private Object lock = new Object(); public Producer(BlockingQueue sharedQueue, int queueSize){ this.sharedQueue = sharedQueue; this.queueSize = queueSize; } public void run() { while(true) { if(sharedQueue.size()== queueSize){ try { synchronized (lock) { sharedQueue.wait(); } } catch (InterruptedException […]