如何使多个线程 运行 并行执行,以便一个接一个地执行线程

How to make multiple threads run parallally such that execution of threads takes place one after the other

我正在尝试实现并行线程执行。例如

t1, t2, and t3 are three threads , each performing a task to print multiplication table. I want to execute them in a sequence

--------------------------------
|   t1    |    t2    |    t3   | 
--------------------------------
|   2     |     3    |     4   |
|   4     |     6    |     8   |
|   6     |     9    |    12   |
|   ..    |    ..    |   ..    |
|------------------------------|

执行顺序:t1--> t2--> t3 --> t1

到目前为止,我能够创建三个独立执行任务的线程

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

public class SynchronizationExample1 {
    public static void main(String[] args) {
        ExecutorService es = Executors.newFixedThreadPool(3);   
        for(int i=1; i<=10; i++){
            es.execute(new Task(i));
        }
        es.shutdown();

        while(!es.isTerminated()){

        }
        System.out.println("finished all task");
    }
}

任务class

public class Task implements Runnable {
    private int i; 
    public Task(int i){
        this.i = i;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+ "Start counter = " + i);
        processMessage();
        System.out.println(Thread.currentThread().getName()+ "End counter");
    }

    public void processMessage(){
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

输出:

pool-1-thread-1Start counter = 1
pool-1-thread-3Start counter = 3
pool-1-thread-2Start counter = 2
pool-1-thread-1End counter
pool-1-thread-1Start counter = 4
pool-1-thread-3End counter
pool-1-thread-3Start counter = 5
pool-1-thread-2End counter
pool-1-thread-2Start counter = 6
pool-1-thread-1End counter
pool-1-thread-1Start counter = 7
pool-1-thread-3End counter
pool-1-thread-3Start counter = 8
pool-1-thread-2End counter
pool-1-thread-2Start counter = 9
pool-1-thread-1End counter
pool-1-thread-1Start counter = 10
pool-1-thread-3End counter
pool-1-thread-2End counter
pool-1-thread-1End counter
finished all task

I am trying to acheive parallal thread execution. for example t1, t2, and t3 are three threads , each performing a task to print multiplication table. I want to execute them in a sequence.

这是一种自相矛盾的说法。

你可以并行或顺序做事,但不能同时做。 (就像运行同时骑自行车!)


正如@Thilo 所述,简单、实用(也是最佳)的解决方案是不要使用多线程来执行此操作。只需使用一个线程和一个 for 循环。

如果您打算使用多个线程执行此操作,则需要线程同步。 (这似乎是您当前代码的问题。您没有同步......只有三个 "free running" 线程和 sleep() 调用。这种方法永远不会可靠。)

例如,

  • 线程 1 打印一行,告诉线程 2 - "your turn",然后等待轮到它
  • 线程 2 打印一行,告诉线程 3 - "your turn",然后等待轮到它
  • 线程 3 打印一行,告诉线程 1 - "your turn",然后等待轮到它
  • 等等

直到你走到尽头。 (然后你需要做一些特别的事情......)

对于每三对线程,此通知可以采用 3 个单独的 "channels"(原始互斥锁、锁存器、信号量、队列等)形式,或者每个线程等待的单个 "channel"轮到它了。

(还有其他方法可以解决这个问题......但我们不需要在这里讨论。)