我在下面编写了一段代码,试图了解多线程。但是,结果不是我所期望的。看起来它在搜索完成执行之前返回了值。我怎样才能让它等到结果准备好然后才获得返回值?
/******************************************************************************
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。
您在for循环内有打印语句System.out.println("array[i] lowestValue: " + lowestValue);
,但在if条件语句外,因此它为数组中的每个元素打印lowestValue
的当前值一次,将打印移到循环外]]