有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使多个线程并行运行,从而使线程一个接一个地执行

我正在尝试实现视差线程执行。比如说

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");
    }
}

任务类

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

共 (1) 个答案

  1. # 1 楼答案

    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循环

    如果您打算使用多个线程执行此操作,则需要线程进行同步。(这就是您当前代码的问题所在。您没有同步…只有三个“自由运行”线程和sleep()调用。这种方法永远不会可靠。)

    比如说,

    • 线程1打印一行,告诉线程2“轮到你了”,然后等待轮到它
    • 线程2打印一行,告诉线程3“轮到你了”,然后等待轮到它
    • 线程3打印一行,告诉线程1“轮到你了”,然后等待轮到它
    • 等等

    直到你走到尽头。(那时你需要做一些特别的事情……)

    对于每三对线程,该通知可以采用3个单独的“通道”(基本互斥体、锁存器、信号量、队列等)的形式,或者采用单个“通道”的形式,其中每个线程等待轮到它

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