[英]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.