首页 > 解决方案 > 在循环中创建线程并等待所有线程在java中完成

问题描述

我是 Java 新手。我最近在学校学习多个线程。我尝试创建一个小程序,可以将任务分成更小的部分,并使用循环在单独的线程中运行每个部分。问题是在循环之后我需要对结果求和并将其打印出来,但是循环之后的打印在线程完成之前运行。

我所有的同学都sleep在打印结果之前添加,但是当线程花费太长时间时,这不起作用。

有没有办法在运行其他代码之前等待循环中的所有线程先完成?

import java.util.Scanner;
import java.util.concurrent.ExecutorService;

import java.util.concurrent.TimeUnit;

public class threatGenerator {
    static int count = 0;
    public static void main(String[] args) throws InterruptedException {
        Scanner sc = new Scanner(System.in);
        System.out.print("Input start: ");
        int start = Integer.parseInt(sc.nextLine());
        System.out.print("Input end: ");
        int end = Integer.parseInt(sc.nextLine());
        
        int threadNumber = (int)Math.ceil((end - start)/100.0) ;

        System.out.println("Running "+threadNumber+" threads.");
       
        for(int i = 0 ;i < threadNumber;i++){
            int temp = start+ 99;
            
            if(temp>end) temp = end;

            String name = String.valueOf(i);
            ThreadDemo thread = new ThreadDemo(name,start,temp);
            thread.start();
            
            start = temp+1;
        }
        Thread.sleep(10);
        System.out.println("\nSum of primes = "+count);
        sc.close();
    }

    public static void awaitTerminationAfterShutdown(ExecutorService threadPool) {
        threadPool.shutdown();
        try {
            if (!threadPool.awaitTermination(60, TimeUnit.SECONDS)) {
                threadPool.shutdownNow();
            }
        } catch (InterruptedException ex) {
            threadPool.shutdownNow();
            Thread.currentThread().interrupt();
        }
    }
}

class ThreadDemo extends Thread {
    private Thread t;
    private String threadName;
    private int start;
    private int end;
    private int num = 0;

    ThreadDemo( String name,int start,int end) {
        threadName= name;
        this.start = start;
        this.end = end;
    }
    public void run() {
        Prime p = new Prime();

        for(int i = start ; i<=end;i++){
            if(p.checkPrime(i)!=true){
                System.out.print("t"+threadName+"-"+i+" ");
                ++num;
            }
        }
        threatGenerator.count = threatGenerator.count + num;
    }
    
    public void setCount(int count){
        this.num=count;
    }

    public int getCount() {
        return this.num;
    }

    public void start () {
        // System.out.println("Starting " + threadName);
        if (t == null) {
            t = new Thread (this, threadName);
            t.start();
        }
    }
}

标签: javamultithreadingloopswaitnotify

解决方案


无论如何要等待循环中的所有线程完成......?

如果您更改程序以保留所有Thread引用(例如,通过将它们添加到ArrayList<Thread>,),那么您可以编写第二个循环来保存join()所有线程。

https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/Thread.html#join()

t.join()等待(即不返回)直到线程t终止。


推荐阅读