java - 在循环中创建线程并等待所有线程在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();
}
}
}
解决方案
无论如何要等待循环中的所有线程完成......?
如果您更改程序以保留所有Thread
引用(例如,通过将它们添加到ArrayList<Thread>
,),那么您可以编写第二个循环来保存join()
所有线程。
https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/Thread.html#join()
t.join()
等待(即不返回)直到线程t
终止。
推荐阅读
- java - 通过继承运行时异常来“绕过” throws 子句
- python - Python 编辑和更新 Excel/Csv 文件
- ionic4 - 离子4刷新后相同的页面而不去登录页面
- javascript - 由于反向代理,无法在生产中获取客户端的 IP
- node.js - 不知道主键的 DynamoDB 查询
- r - 添加考虑颜色、形状和线型的组合图例,同时保留原始图例
- python - Python ML 线性回归对象不可调用
- python - 获取列的名称并在数据框 pandas 中从中创建数据
- asp.net - asp fileupload 控件停止使用 android 8
- windows - PowerShell 脚本尝试复制不存在的文件夹