我创建了一个程序,将线性搜索(搜索 -1)划分为 4 个单独的线程。
public class main {
static boolean found = false;
public static void main(String[] args) {
// TODO Auto-generated method stub
int threadCount = 4; //amount of threads to use
Random rand = new Random();
Searcher[] s_arr = new Searcher[threadCount]; //array of threads
int[] arr = new int[10000]; //array to search through
for (int i = 0; i < arr.length; i++) //randomizing #'s in array
arr[i] = (int) (rand.nextFloat() * 1000);
int randIndex = rand.nextInt(arr.length); //choose random index
arr[randIndex] = -1; //set random index to = -1
for (int i = 0; i < threadCount; i++) { //
s_arr[i] = new Searcher(Arrays.copyOfRange(arr, i * (arr.length/threadCount), (i+1) * (arr.length/threadCount)),
(int) (i), i); //assign subarray for this thread to search through
System.out.println(s_arr[i].wait);
s_arr[i].start();
}
//CODE IN QUESTION HERE ----------------------------
//while (!found) ;
while (!found) //wait until value is found
{
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
我已经标记出了有问题的代码,在使用第一个(注释掉的)while 循环时,程序不会超出该点,但是如果我切换并使用它正下方的另一个 while 循环(强制它的那个循环)每个迭代器等待 1 毫秒)程序运行得很好。
为什么会这样?是否有更有效/实用的方法来完成这项任务?
不负相思意
相关分类