我是多线程新手。我需要使用多个线程通过部分和来计算积分。我想知道是否所有线程都完成了计算以显示总和,我正在使用 sleep(500) 来完成它,但这很愚蠢。我怎样才能以正确的方式做到这一点?
public class MainClass {
private static int threadCount=10;
public static double generalSum=0;
private static ArrayList<CalculatingThread> threads;
public static void main(String[] args){
Calculator.setA(0);
Calculator.setB(2);
Calculator.setN(500);
threads=new ArrayList<CalculatingThread>();
int div=500/threadCount;
for (int i=0; i<div;i++){
CalculatingThread thread=new CalculatingThread();
thread.setJK(i*10,(i+1)*10-1);
thread.start();
threads.add(thread);
}
try {
Thread.currentThread().sleep(500);
System.out.println(generalSum);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class CalculatingThread extends Thread {
private int j;
private int k;
@Override
public void run(){
System.out.println("Partial sum: " + Calculator.calcIntegral(j, k));
Calculator.addToSumm(Calculator.calcIntegral(j, k));
//this.notify();
}
public void setJK(int j,int k) {
this.j = j;
this.k=k;
}
}
public class Calculator {
private static double a;
private static double b;
private static int n;
private static double InFunction(double x){
return Math.sin(x);
}
private double sum=0;
public static void setA(double a) {
Calculator.a = a;
}
public static void setB(double b) {
Calculator.b = b;
}
public static void setN(int n) {
Calculator.n = n;
}
public static double calcIntegral(int j,int k)
{
double result, h;
int i;
h = (b-a)/n; //Шаг сетки
result = 0;
for(i=j; i <= k; i++)
{
result += InFunction(a + h * i - h/2); //Вычисляем в средней точке и добавляем в сумму
}
result *= h;
return result;
}
public static synchronized void addToSumm(double sum){
MainClass.generalSum+=sum;
}
}
附注抱歉,我知道代码很愚蠢,我稍后会重构它
最佳答案
替换
Thread.currentThread().sleep(500);
与
for (Thread thread : threads) {
thread.join();
}
这将使主线程等待,直到所有创建的线程完成。也可以引用wait until all threads finish their work in java
关于java - 多线程 java xsync,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26841699/