如何用线程创建循环(在一个循环中创建几个新线程)



我如何创建一个循环(或者其他更好的方法(来创建一些新线程。到目前为止,我有2个生产者和消费者线程。但我想创建,例如,5个生产者和5个消费者,并且生产/消费的每个线程都有一个不同的"线程";产品";,两个线程不能执行相同的操作。

我希望它是这样的:

Produced thread0  produce 0 
Consume thread0  consume 0
....
Produced  thread4 produce 4
Consume  thread4  consume 4

谢谢你的每一个暗示。

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class ProducerConsumer {
public static void main(String[] args) throws InterruptedException {
BlockingQueue<Integer> blockingQueue = new ArrayBlockingQueue<>(2);
Thread producerThread = new Thread(new Runnable() {
@Override
public void run() {
try {
int value = 0;
while (true) {
blockingQueue.put(value);
System.out.println("Produced " + value);
value++;
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread consumerThread = new Thread(new Runnable() {
@Override
public void run() {
try {
while (true) {
int value = blockingQueue.take();
System.out.println("Consume " + value);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
producerThread.start();
consumerThread.start();
producerThread.join();
consumerThread.join();
}
}
  • 使用线程池(Executors.newFixedThreadpoolExecutors.newCachedThreadPool(
  • 不要忘记使用synchronized块来管理资源的线程同步
  • 对于将由多个线程同时写入/读取的值,请使用volatile关键字(请参阅volatile关键字的作用是什么?(
  • 为了清晰起见,我使用了lambda语法来重新定义可运行文件
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ProducerConsumer {
private static volatile int prodValue = 0;
private static final Object valueSync = new Object();
public static void main(String[] args) throws InterruptedException {
final BlockingQueue<Integer> blockingQueue = new ArrayBlockingQueue<>(2);
final ExecutorService threadPool = Executors.newCachedThreadPool();
final Runnable producer = () -> {
try {
while (true) {
synchronized(valueSync) {
blockingQueue.put(prodValue);
System.out.println(Thread.currentThread().getId() + " Produced " + prodValue);
prodValue++;
}
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
};
final Runnable consumer = () -> {
try {
while (true) {
int value = blockingQueue.take();
System.out.println(Thread.currentThread().getId() + " Consumed " + value);
Thread.sleep(1200);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
};
for (int i = 0; i < 5; i++) { //Create 5 threads of each
System.out.println("Loop " + i);
threadPool.execute(producer);
threadPool.execute(consumer);
Thread.sleep(500); //Wait a little
}
System.out.println("Loop done");
//Wait for all threads to complete with timeout
threadPool.awaitTermination(15, TimeUnit.SECONDS);
System.out.println("STOP !");
//Forceful shutdown of all threads (will happen as all threads are in a while(true) loop
threadPool.shutdownNow();
}
}

关于同步:在这里,您希望将您的值添加到队列中,并立即(原子(递增。操作周围的synchronized阻止线程同时运行这段代码,这将导致同一个值多次添加到队列中,然后多次递增(如果将Thread.sleep值减少到接近0的值并删除synchronized块,就会发生这种情况(。

我本可以使用blockingQueue作为synchronized的参数,但选择使用专用对象使其更加明显

最新更新