java - 多线程在完成处理之前返回数字(JAVA)

标签 java multithreading

我编写了下面的代码来尝试理解多线程。然而,结果并不是我所期望的。看起来它在搜索完成执行之前返回了值。如何让它等到结果准备好然后才获取返回值?

/******************************************************************************

                            Online Java Compiler.
                Code, Compile, Run and Debug java program online.
Write your code in this editor and press "Run" button to execute it.

*******************************************************************************/
import java.util.concurrent.Executor;  
import java.util.concurrent.Executors;  
import java.util.concurrent.ThreadPoolExecutor;  
import java.util.concurrent.TimeUnit;  
import java.util.ArrayList;

//Finding the smallest number in an array
public class Main
{
    public static class Search implements Runnable {
        private int[] array;
        private int lowestNumber; 
        private int taskNumber;

        public Search(int[] array, int taskNumber){
            this.lowestNumber = 0;
            this.taskNumber = taskNumber;
            this.array = array;
        }

        public int getLowestNumber(){
            return lowestNumber;
        }

        protected void setLowestNumber(int lowestNumber){
            this.lowestNumber = lowestNumber;
        }

        protected void searchArrayLowestNumber(){
            int lowestValue = 0; 
            int arrayLength = array.length;

            for(int i = 0; i < arrayLength; i++){
                if( i == 0 ){
                    lowestValue = array[i];
                }
                if(array[i] < lowestValue){
                    lowestValue = array[i];
                } 
                System.out.println("array[i] lowestValue: " + lowestValue);
            }
            setLowestNumber(lowestValue);

        }

        public void run(){
                System.out.println("Accessing search...task number: " + taskNumber);
                searchArrayLowestNumber();

        }

    }

    public static void main(String[] args) throws InterruptedException {

        ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(2);
        int[][] arrayA = {{12, 13, 1}, {10, 34, 1}};

        for (int i = 0; i <= 1; i++) 
        {
            int[] tempArray = new int[3];
            for(int j = 0; j < 3; j++){
                tempArray[j] = arrayA[i][j];
            }
            Search searchLowestNumber = new Search(tempArray, i);
            int number = searchLowestNumber.getLowestNumber();
             try{
                Long duration = (long) (Math.random() * 10);
                System.out.println("Lowest number for this thread " + i + " is " + number);
                TimeUnit.SECONDS.sleep(duration); 
             }catch (InterruptedException e) {
                e.printStackTrace();
             }

            executor.execute(searchLowestNumber);
        }
        executor.shutdown();
    }
}

目前的结果如下:

Lowest number for this thread 0 is 0                                                                                                                                               
Lowest number for this thread 1 is 0                                                                                                                                               
Accessing search...task number: 0                                                                                                                                                  
array[i] lowestValue: 12                                                                                                                                                           
array[i] lowestValue: 12                                                                                                                                                           
array[i] lowestValue: 1                                                                                                                                                            
Accessing search...task number: 1                                                                                                                                                  
array[i] lowestValue: 10                                                                                                                                                           
array[i] lowestValue: 10                                                                                                                                                           
array[i] lowestValue: 1 

我实际上期望两个线程最后都返回 1。

最佳答案

有两件事你需要解决 首先,您的打印语句 System.out.println("array[i] lowerValue: "+ lowerValue); 在 for 循环内但在 if 条件之外,因此它打印的是当前值lowestValue 对于数组中的每个元素一次,如果您希望仅在更新变量时打印该值,则应将其移至 if 语句中。

其次,您必须将此表达式 System.out.println("Lowest number for this thread "+ i + "is "+ number); 移动到调用 executor.execute 之后(searchLowestNumber); 因为搜索实际上正在发生,否则您将打印的数字是您在类“0”的构造函数中设置的数字,因为它尚未更新那一点

关于java - 多线程在完成处理之前返回数字(JAVA),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58946538/

相关文章:

java - 通过套接字发送 10 MB 的缓冲区 - block 还是整个 10MB?

ios - CPU 运行率超过 100%

C++ - 线程同步

java - JAVA通过并发在静态方法中实现唯一ID号

multithreading - 我正在运行哪个 openmp 时间表?

java - jQuery js 文件未加载

java - 动态代码分析和渗透测试之间的区别?

java - 如何引用资源文件夹中的javafx fxml文件?

java - 变量声明后应出现错误 ";",,

安卓后台线程