Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/394.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何保证主线的最后光洁度_Java_Multithreading - Fatal编程技术网

Java 如何保证主线的最后光洁度

Java 如何保证主线的最后光洁度,java,multithreading,Java,Multithreading,我研究Java多线程编程。我的任务是实现一个多线程程序来计算矩阵积。每个线程负责生成矩阵的不同行。任务说明:“在主程序中使用join()等待所有线程完成,然后再打印出结果矩阵” 下面是我的代码: MatrixProduct.java package multythreading; import java.util.Arrays; public class MatrixProduct { public static Matrix a; public static Matrix

我研究Java多线程编程。我的任务是实现一个多线程程序来计算矩阵积。每个线程负责生成矩阵的不同行。任务说明:“在主程序中使用
join()
等待所有线程完成,然后再打印出结果矩阵”

下面是我的代码:

MatrixProduct.java

package multythreading;

import java.util.Arrays;

public class MatrixProduct {

    public static Matrix a;
    public static Matrix b;

    static {
        a = new Matrix(new int[][]{{1, 2, 3, 4, 5, 6, 7, 8, 9, 10},
                                   {4, 5, 64, 5, 6, 7, 8, 9, 10, 11},
                                   {7, 8, 94, 5, 6, 7, 8, 9, 10, 12},
                                   {7, 8, 94, 5, 6, 7, 8, 9, 10, 13},
                                   {4, 5, 64, 5, 6, 7, 8, 9, 10, 14},
        });
        b = new Matrix(new int[][]{{2, 1, 3},
                                   {4, 2, 1},
                                   {6, 4, 5},
                                   {6, 4, 5},
                                   {4, 2, 1},
                                   {2, 1, 3},
                                   {4, 2, 1},
                                   {6, 4, 5},
                                   {6, 4, 5},
                                   {4, 2, 1}});
    }

    public static void main(String [] args) {
        Thread[] threads = new Thread[a.getRowNum()];
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(new ResultMatrixLine(i), "Line number " + i + " computation thread");
            threads[i].start();
        }

        for (Thread t: threads) {
            if (t.isAlive()) {
                try {
                    System.out.println(t.getName() + " : " + t.getState()  + " still alive");
                    t.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("All computation threads terminated and the resulting matrix is ready");
    }
}

class ResultMatrixLine implements Runnable {

    private int lineNumber;

    public ResultMatrixLine(int lineNumber) {
        this.lineNumber  = lineNumber;
    }

    @Override
    public void run() {
        System.out.println("Line number = " + lineNumber + ": " + Arrays.toString(getResultLine()));
    }

    private int[] getResultLine() {
        int[] result = new int[MatrixProduct.b.getColumnNum()];
        for (int i = 0; i < MatrixProduct.b.getColumnNum(); i++)
            for (int j = 0; j < MatrixProduct.a.getColumnNum(); j++)
                result[i] += MatrixProduct.a.getMatrixElement(lineNumber, j)*MatrixProduct.b.getMatrixElement(j, i);
        return result;
    }
}

class Matrix {
    private final int columnNum;
    private final int rowNum;
    private final int[][] matrix;

    public Matrix(int[][] matrix) {
        this.columnNum = matrix[0].length;
        this.rowNum = matrix.length;
        this.matrix = matrix;
    }

    public int getColumnNum() {
        return columnNum;
    }

    public int getRowNum() {
        return rowNum;
    }

    public int getMatrixElement(int columnIndx, int rowIndx) {
        return matrix[columnIndx][rowIndx];
    }
}
包多线程;
导入java.util.array;
公共类MatrixProduct{
公共静态矩阵a;
公共静态矩阵b;
静止的{
a=新的矩阵(新的int[][{{1,2,3,4,5,6,7,8,9,10},
{4, 5, 64, 5, 6, 7, 8, 9, 10, 11},
{7, 8, 94, 5, 6, 7, 8, 9, 10, 12},
{7, 8, 94, 5, 6, 7, 8, 9, 10, 13},
{4, 5, 64, 5, 6, 7, 8, 9, 10, 14},
});
b=新矩阵(新int[][{{2,1,3},
{4, 2, 1},
{6, 4, 5},
{6, 4, 5},
{4, 2, 1},
{2, 1, 3},
{4, 2, 1},
{6, 4, 5},
{6, 4, 5},
{4, 2, 1}});
}
公共静态void main(字符串[]args){
线程[]线程=新线程[a.getRowNum()];
对于(int i=0;i

结果矩阵的行是独立计算的,所以我唯一关心的是正确地使用
main()
方法中的
join()
。我的意思是,在主线程的末尾,所有其他线程都必须终止,以便生成的矩阵准备就绪。我的决定乍一看效果很好,但我希望看到对它的任何评论。

以下是我通过修改代码创建的解决方案:

在矩阵乘积中添加了ArrayList,并在公共作用域中添加了一个函数以从中删除线程:

private static ArrayList<ResultMatrixLine> threads = new ArrayList<>();


public static void main(String [] args) {
    for (int i = 0; i < a.getRowNum(); i++) {
        // Create a new ResultMatrixLine thread
        ResultMatrixLine thread = new ResultMatrixLine( i );
        // Keep the thread handy for manipulation later
        threads.add( thread );
        // Create a new thread
        thread.start();
    }

    threads.stream().forEach( (thread) -> {
        if( thread.isAlive() ) {
            try {
                thread.join( 1000 );
            } catch( InterruptedException ex ) {
                ex.printStackTrace( System.out );
            }
        }
    });

    System.out.println("All computation threads terminated and the resulting matrix is ready");

}

对线程使用join()方法,在创建所有线程之后,它将在ArrayList中循环并检查是否有任何线程处于活动状态。如果是这样的话,就加入()它们。

我认为这更适合codereview…
t。join()
做的正是您期望它做的:它等待线程
t
终止。您应该看看java streams API。此API不允许您自己创建
线程。另一方面:您应该明确了解多线程的一般情况以及如何执行和不执行多线程(即:为每个小任务生成一个新线程-例如计算矩阵乘积的一行)。关于多线程的有用帮助程序可以帮助您避免自己进行AD管理,这是一个很好的开端。对于Java,它们是
Java.future
和新的并行流API。使用join()可以使线程按顺序运行,对吗?不是一次全部吗?我只是简单地浏览了一下您的问题,但作为流API的替代方案,我建议您仔细阅读,看看是否可以利用它。invokeAll可能就是你要找的。(别忘了在最后关闭!)不要转储代码,解释你所做的每一个更改以及为什么这么做。@Polygenme对你更好吗?这不是什么对我更好,而是什么对未来有类似问题的读者更好。毕竟,它的目标是建立一个知识库。注释代码是一个开始,但它与实际解释东西是如何工作的并不相同。此外,我根本不明白你的答案是怎么回事
thread.run()
调用runnables
run
方法,它实际上并没有启动线程,所以工作不是同时完成的,这显然是OP想要的。@Polygenme你说得对。那是我的错。我注意到我上面代码的缺陷。修理。。。
Line number = 1: [670, 423, 503]
Line number = 3: [876, 556, 667]
Line number = 0: [254, 151, 165]
Line number = 4: [682, 429, 506]
Line number = 2: [872, 554, 666]
All computation threads terminated and the resulting matrix is ready