我写了下面的代码来尝试理解多线程。但是,结果不是我所期望的。看起来它在搜索完成执行之前返回了值。我怎样才能让它等到结果准备好然后才获得返回值?
/******************************************************************************
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。
答案 0 :(得分:0)
您需要修复两件事
首先,您需要在for循环内拥有打印语句System.out.println("array[i] lowestValue: " + lowestValue);
,但在if条件语句之外,因此,如果您希望仅将lowestValue
的当前值对数组中的每个元素打印一次,在变量更新时打印出来,则应将其移至if语句中。
第二,您必须在调用System.out.println("Lowest number for this thread " + i + " is " + number);
之后将表达式executor.execute(searchLowestNumber);
移动到,因为那里实际上正在进行搜索,否则,将要打印的数字就是您要设置的数字在您的类“ 0”的构造函数中,因为此时尚未对其进行更新