【问题标题】:Execute a same action multiple times in parallel and looping on it并行多次执行相同的操作并循环执行
【发布时间】:2020-11-10 11:08:11
【问题描述】:

我正在尝试向自己介绍并行编程,但我不确定我的想法是否正确。我有同一个类的多个实例,我想同时执行同一个任务。在此之后,线程等待 x 时间并再次执行操作。

我目前正在考虑这样的事情

public class RunnableT implements Runnable {

 @Override
 public void run() {

     while(!Main.stop) {
         //Perform task
         //Wait to mask next action
     }

 }
}

所以我会有一个这样的主线程:

public class Main {
    
    public static boolean stop;

    public static void main(String[] args) {

        stop = false;
        
        Thread t1 = new Thread(new RunnableT());
        t1.start();
        Thread t2 = new Thread(new RunnableT());
        t2.start();

        for(int i = 0; i < 10; i++) {
            //Call t1 & t2 to perform the action
            //Wait a second
            //Loop
        }
    
        stop = true;
    }

}

我知道我做错了,但我不知道该怎么做。

【问题讨论】:

    标签: java multithreading parallel-processing


    【解决方案1】:

    你不能Call t1 &amp; t2 to perform the action。通常线程之间的交互是使用(同步)队列完成的,最佳候选者是ArrayBlockingQueue。在主类中创建ArrayBlockingQueue,让主线程将任务放入其中,并让工作线程从中读取并执行任务。

    UPDT。如果您希望每个任务由每个线程执行,则创建2个队列,每个线程一个,并让每个线程只读取自己的线程,而主线程创建下一个任务并将其放在两个线程中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-17
      • 2014-09-14
      • 1970-01-01
      • 1970-01-01
      • 2013-04-05
      • 1970-01-01
      • 2015-05-13
      • 1970-01-01
      相关资源
      最近更新 更多