I'm trying to spin up many threads in a Producer-Consumer model in Java and for some reason it's not doing what it's supposed to.
I have code that does
List<Thread> consumers = new ArrayList<>();
for (int i = 0; i < noOfThreads; i++) {
Thread consumer = new Thread(new Runnable() {
String name = "Thread-" + UUID.randomUUID();
@Override
public void run() {
try {
pc.consume(name);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
consumers.add(consumer);
consumer.start();
consumer.join();
}
where pc
is a ProducerConsumer whose consume method is
public void consume(String name) throws InterruptedException {
while (true) {
synchronized (this) {
while (subQueue.size() == 0) {
wait(2000);
}
Subscriber sub = subQueue.poll();
System.out.println(name);
uploadEndpointToPinpoint(sub);
notify();
}
}
}
So, when I run this I expect to see it print out 10 different UUIDs, indicating that there are 10 threads running - but that's not happening. Instead I just get:
Thread-c42ac697-d4ad-4944-a20e-907952f5d5ab
Thread-c42ac697-d4ad-4944-a20e-907952f5d5ab
Thread-c42ac697-d4ad-4944-a20e-907952f5d5ab
Thread-c42ac697-d4ad-4944-a20e-907952f5d5ab
Thread-c42ac697-d4ad-4944-a20e-907952f5d5ab
Thread-c42ac697-d4ad-4944-a20e-907952f5d5ab
Thread-c42ac697-d4ad-4944-a20e-907952f5d5ab
which means that it only started one of the threads. Why is the for loop not doing what I think it should?
Any and all help would be appreciated.
Calling Thread#join() blocks the current thread until the target thread is not running anymore. In your loop you're essentially starting a single thread and then waiting for it to complete, which is why you only see one thread. If you want to wait for all the threads to complete you need to move the join() call outside the loop that creates the thread.
List<Thread> consumers = new ArrayList<>();
for (int i = 0; i < noOfThreads; i++) {
Thread consumer = new Thread(new Runnable() {
String name = "Thread-" + UUID.randomUUID();
@Override
public void run() {
try {
pc.consume(name);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
consumers.add(consumer);
consumer.start();
}
for (Thread thread : consumers) {
thread.join();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.