[英]Java using wait/notify methods on threads that do same thing
我試圖了解Java監視器,然后想到的問題是如何使運行相同同步方法的線程等待? 我正在嘗試制作一個簡單的程序,該程序將使3個線程使用相同的方法添加到N個元素1中,總共進行10 000次,並且我想知道如何使其他線程在執行添加方法和notifyAll之后等待。如果我要同時啟動所有它們,那就完成了。
這是我編寫的沒有等待/通知功能的程序:
class Swapper implements Runnable{
int number;
Swapper(int number){
this.number=number;
}
@Override
public void run() {
while (mainClass.counter>0){
mainClass.incArrayElement(number);
}
}
}
public class mainClass {
public static volatile int counter = 10000;
public static volatile int[] testArray = new int[]{0,0,0};
public static synchronized void incArrayElement(int index){
if (counter>0) {
testArray[index - 1]++;
counter--;
}
else {
return;
}
}
public static void main(String[] args) throws InterruptedException {
Thread thread1 = new Thread(new Swapper(1));
Thread thread2 = new Thread(new Swapper(2));
Thread thread3 = new Thread(new Swapper(3));
thread1.start();
thread2.start();
thread3.start();
thread1.join();
thread2.join();
thread3.join();
int checkSum = 0;
for (int i = 0; i < testArray.length; i++) {
System.out.println(testArray[i]);
checkSum+=testArray[i];
}
System.out.println(checkSum);
}
}
當線程調用您類的同步方法“ incArrayElement”時,它將獲取該對象的鎖,只要先前已獲得該鎖的線程不釋放該鎖,任何新線程都無法調用同一對象的任何同步方法。 因此,所有其他線程將被阻塞,直到執行完成。
那么,為什么您需要讓線程調用wait(),因為它們已經被阻塞並正在等待。
不幸的是,您的示例選擇不當。
聲明為synchronized
的方法的控制方式是其他線程無法調用它,除非它已完成執行。 然后,其中一個線程再次調用此方法。 不能真正告訴“哪個線程”,因為您無法控制它。 使用wait
和notify
功能也不會控制您。 因此,如果這是您想要的,那么您將無法實現自己想要的。 它對您來說仍然不確定。
如果僅確保一次僅由一個線程調用該方法,那么您已經具有該行為,無需wait
或notify
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.