Java中的多线程(并行代码比串行代码慢)

时间:2022-12-14 20:59:22

Four threads are generated and passed their range needed to loop a matrix in order to do some operation. Essentially, my desire is to take a for loop and break up the work by four threads.

生成四个线程并传递其循环矩阵所需的范围以执行某些操作。从本质上讲,我的愿望是采用for循环并通过四个线程分解工作。

GE_threaddiv t = new GE_threaddiv(k + 1,toPass + (k+1),k,A[k][k],"1");
        GE_threaddiv t2 = new GE_threaddiv(toPass + (k+1),toPass*2 + (k+1),k,A[k][k],"2");
        GE_threaddiv t3 = new GE_threaddiv(toPass*2 + (k+1),toPass*3 + (k+1),k,A[k][k],"3");
        GE_threaddiv t4 = new GE_threaddiv(toPass*3 + (k+1),toPass*4 + (k+1),k,A[k][k],"4");
        t.start();
        t2.start();
        t3.start();
        t4.start();
        try {
            t.join();
            t2.join();
            t3.join();
            t4.join();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

Each thread starts a for loop with the specified range a being the start and b being the end of the segment (passed in when the thread was made). A is a global matrix and temp is a value from A passed into the thread on creation.

每个线程启动一个for循环,其中指定的范围a是开始,b是段的结尾(在创建线程时传入)。 A是全局矩阵,temp是A创建时传递给线程的值。

public void run() 
    { 
        try
        { 
                        for(int j = a; j < b; j++) {
                            A[c][j] = A[c][j]/temp;
                        }

        } 
        catch (Exception e) 
        { 
            System.out.println ("Exception is caught"); 
        } 
    } 

My implementation is working, however it is drastically slower (magnitudes) than if I were to run the for loop in serial. The larger the data set, the slower the time. The threads are confirmed to be running side by side. My guess is that the degradation in efficiency is coming from how each thread is involved with memory access. Any help would be greatly appreciated!

我的实现正在运行,但它比我在串行中运行for循环要慢得多(幅度)。数据集越大,时间越慢。确认线程并排运行。我的猜测是效率的下降来自于每个线程如何参与内存访问。任何帮助将不胜感激!

1 个解决方案

#1


2  

java8 features can resolve your issue, Java8 parallel streams for multithreading are for performance and takes very less time. I think this link can help you a bit

java8功能可以解决您的问题,用于多线程的Java8并行流用于提高性能并且花费的时间非常少。我认为这个链接可以帮助你一点

list.parallelStream().forEach(element -> doWork(element));

[Java8 Multithreading]

#1


2  

java8 features can resolve your issue, Java8 parallel streams for multithreading are for performance and takes very less time. I think this link can help you a bit

java8功能可以解决您的问题,用于多线程的Java8并行流用于提高性能并且花费的时间非常少。我认为这个链接可以帮助你一点

list.parallelStream().forEach(element -> doWork(element));

[Java8 Multithreading]