java - 多线程 java xsync

标签 java multithreading

我是多线程新手。我需要使用多个线程通过部分和来计算积分。我想知道是否所有线程都完成了计算以显示总和,我正在使用 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/

相关文章:

java - 中断线程时出现 IllegalMonitorStateException

c# - c#线程间数据传递

python - Tensorflow 中网络权重的线程安全克隆?

java - 如何使用 Spark-Java 配置上下文路径

c++ - 我们可以在 Sockets Map 上使用读写锁吗?

Java SafeVarargs 注释,是否存在标准或最佳实践?

java - 使用maven从git获取代码+执行构建+打包成jar+最后压缩包含jar和资源的完整文件夹

Python - 如何使以下函数线程化?

java - 增强 for 循环上的 ArrayIndexOutOfBounds

java - 如何在 Spring Boot 中更新子实体和父实体?