创建具有唯一 ID 的多个线程(线程不重叠)

creating multiple threads with a unique id (threads do not overlap)

更新

我正在解决一个生产者/消费者问题,我想创建一些生产者和消费者(多个线程),我有一个问题,我如何才能正确地创建多个线程,这样一个任务就不会由两个执行线程(每个线程执行不同的任务)。

代码: 我试着像这里这样循环进行:

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

    public class ProducerConsumerExample {
    
        public static void main(String[] args) {
    
            BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(10);
    
            for (int i = 0; i < 10 ; i++) {
                Producer producer = new Producer(blockingQueue);
                Consumer consumer = new Consumer(blockingQueue);
    
                Thread producerThread = new Thread(producer);
                Thread consumerThread = new Thread(consumer);
    
                producerThread.start();
                consumerThread.start();
            }
        }
    }

输出: 但它不起作用,因为线程相互重叠

Producer produced : 1619703940537
Producer produced : 1619703940537
Producer produced : 1619703940537
Producer produced : 1619703940537
consumed gets: 1619703940537
consumed gets: 1619703940537
consumed gets: 1619703940537
consumed gets: 1619703940537
Producer produced : 1619703940537
consumed gets: 1619703940537

您正在寻找的是线程池。 Java 中包含各种实现,它们应该开箱即用。这是我从 javatpoint:

中得出的定义

Java Thread pool represents a group of worker threads that are waiting for the job and reuse many times. In case of thread pool, a group of fixed size threads are created. A thread from the thread pool is pulled out and assigned a job by the service provider.

您可以查看以下页面了解更多信息:

https://www.baeldung.com/thread-pool-java-and-guava https://docs.oracle.com/javase/tutorial/essential/concurrency/pools.html

您看到多个线程使用相同的 System.currentTimeMillis() 值,这使得无法判断发生了什么。将您传递到队列中的令牌更改为每个生产者唯一并包含线程名称:

public void run() {
    int counter=0;
    while (true) {

        try {
            String token = Thread.currentThread().toString() + "#"+(counter++);
            this.blockingQueue.put(token );
            System.out.println("Producer produced nr: " + token );
        } catch (InterruptedException e ) {
            System.out.println("Producer was interrupted");
        }
        sleep();
    }
}

更改 Consumer.run() 以也打印线程名称,您将更清楚地看到哪个 Consumer 实例正在消费每个操作以及来自哪个 Producer:

System.out.println("consumer "+Thread.currentThread()+" gets: " + element);

这将有望证明这些是多个生产者 + 消费者处理程序以及生产者-消费者从同一 BlockingQueue 发送和接收项目的不同排列。