【发布时间】:2021-06-24 18:56:09
【问题描述】:
我是 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();
}
}
}
【问题讨论】:
-
更新静态变量
threatGenerator.count时需要独占控制。否则,您可能无法得到正确的结果。 -
看起来像是 java.util.concurrent.CountDownLatch 的工作。
-
或者,您可以考虑the following answer。
-
请输入正确的大小写和英文。这个网站更像维基百科,而不是一个休闲聊天室。
-
将对所有创建和启动的线程的引用存储到一个列表中,然后在每个线程上调用 .join()。 .join() 方法是专为像你这样的情况设计的
标签: java multithreading loops wait notify