我正在嘗試通過為每一行使用一個執行緒來搜索陣列中第 0 次出現的次數,然后如果有 1 個執行緒發現出現則中斷所有執行緒。我閱讀了多個問題和答案,但找不到簡單的方法,我嘗試使用變數“找到”來不運行其他執行緒。但是,它不起作用,我無法弄清楚問題所在。我主要想使用interrupt()而不是使用變數。任何幫助,將不勝感激。
搜索類
public class Search extends Thread {
int low;
int high;
int[][] array;
static int id=0;
private static boolean found = false;
private boolean done = false;
public Search(int[][] array, int low, int high) {
id ;
this.array = array;
this.high = high;
this.low= low;
}
public void run(){
whileLoop: while(!found && !done){
for(int i = low; i < high; i ){
for(int j = 0; j < array[i].length; j ){
if(array[i][j] == 0){
System.out.println("Found at: " i " " j " By thread " id);
found = true;
done = true;
break whileLoop;
}
}
}
done = true;
}
}
}
主班
public class Main{
public static void main(String[] args){
int[][] array = {{3,0,2,3,0,5},{2,4,0,2,6,5},{4,1,2,4,6,5},{0,2,1,4,0,5},{4,5,6,0,7,1},{9,7,4,1,1,3}}; //6 zeros
SearchArray searchArray = new SearchArray();
searchArray.sArray(array);
}
}
class SearchArray{
public void sArray(int[][] array){
int noThreads = array.length;
Search[] threads = new Search[noThreads];
for(int i = 0; i < threads.length; i ){
threads[i] = new Search(array, i*1 , (i 1) * 1);
threads[i].start();
}
}
}
輸出:
Found at: 0 1 By thread 5
Found at: 3 0 By thread 6
Found at: 1 2 By thread 5
Found at: 4 3 By thread 6
uj5u.com熱心網友回復:
你的found變數不是volatile,這意味著某個執行緒找到之后,并且這個執行緒設定found為true,其他執行緒無法立即感知到它,他們會繼續尋找。
但是即使設定為volatile,也是不夠的,因為多個執行緒可能同時找到它。
所以,如果你想嚴格控制只有一個執行緒會列印Found at:...,你需要使用 alock而不是volatile(lock->check->act):
public void run(){
for(int j = 0; j < array[low].length; j ){
if (found) {
break;
}
if(array[low][j] == 0){
// lock,check,act
// if found, lock
// array here can be a lock, since all threads share this array
synchronized (array) {
// check
if (found) {
break;
}
found = true;
System.out.println("Found at: " low " " j " By thread " id);
break;
}
}
}
}
uj5u.com熱心網友回復:
首先,使用volatile關鍵字是必要的,因為您正在處理由不同執行緒共享和使用的變數。
我建議只將行傳遞給執行緒,而不是整個陣列。那將是不需要的。最后,您可以使用一個標志來檢查是否找到了 0。如果找到,請停止執行緒。
下面的示例滿足您的需求。
// the volatile keyword is important
public static volatile int[][] array = {{3,0,2,3,0,5},{2,4,0,2,6,5},{4,1,2,4,6,5},{0,2,1,4,0,5},{4,5,6,0,7,1},{9,7,4,1,1,3}}; //6 zeros
public static volatile boolean found = false;
public static void main(String[] args)
{
for (int i = 0; i < array.length; i ) // Iterate through each row
{
int finalI = i;
Thread th = new Thread() // Create a new thread for each row
{
@Override
public void run()
{
for (int j = 0; j < array[finalI].length; j ) // Each thread will iterate through each element
{
if(found) // If the element 0 was found, then break and stop the thread
{
System.out.println("Another thread found 0, so stopping this thread.");
break;
}
if(array[finalI][j] == 0) // If this is the thread that finds 0, then log and set flag to true
{
System.out.println(this.getName() " found 0 at index " finalI "," j);
found = true;
break;
}
}
}
};
th.start(); // Start each thread...
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/371825.html
