java关于线程等待/通知
我是java线程概念的初学者。我通过实现等待和通知机制做了一个小程序,编码如下:-
例如。爪哇
import comp.samplecheck;
public class Example extends Thread {
public static void main(String[] args) {
samplecheck sample = new samplecheck("First");
samplecheck sample1 = new samplecheck("Second");
samplecheck sample2 = new samplecheck("Third");
samplecheck sample4 = new samplecheck("Fourth");
samplecheck sample5 = new samplecheck("Fifth");
sample.initiate(sample);
sample1.initiate(sample1);
sample2.initiate(sample2);
try {
Thread.sleep(1000);
sample4.samplefunc(sample4);
}
catch(InterruptedException e) {
System.out.println("Exception "+e);
}
}
}
抽样检查。爪哇
package comp;
import java.util.List;
import java.util.ArrayList;
public class samplecheck extends Thread {
String get_text;
samplecheck objs;
static List arr = new ArrayList();
public samplecheck(String str) {
this.get_text = str;
}
public void run() {
synchronized(arr) {
System.out.println(objs.getName()+" Started Processing");
try {
arr.wait();
}
catch(InterruptedException e) {
System.out.println("Exception "+e);
}
System.out.println("Initial Array Elements Size "+arr.size());
for(int i=0; i<100 ; i++){
arr.add(i);
}
System.out.println("After Array Elements Size "+arr.size());
System.out.println("An Object Is Notified");
}
}
public void initiate(samplecheck obj) {
objs = obj;
objs.start();
}
public void samplefunc(samplecheck obj) {
objs = obj;
synchronized(arr) {
System.out.println("Notification Process");
System.out.println("After Array Elements Size "+arr.size());
arr.notify();
}
}
}
在samplecheck中的samplefunc函数中。java如果我给出arr.notify(),我就能够得到正确的输出
Thread-0 Started Processing
Thread-1 Started Processing
Thread-2 Started Processing
Notification Process
After Array Elements Size 0
Initial Array Elements Size 0
After Array Elements Size 100
An Object Is Notified
但是如果arr.notifyAll()而不是arr.notify(),则输出为
Thread-0 Started Processing
Thread-2 Started Processing
Thread-1 Started Processing
Notification Process
After Array Elements Size 0
Initial Array Elements Size 0
After Array Elements Size 100
An Object Is Notified
Initial Array Elements Size 100
After Array Elements Size 200
An Object Is Notified
Initial Array Elements Size 200
After Array Elements Size 300
An Object Is Notified
但是根据编码透视图,即使我给notifyAll,只有一个获得数组“arr”锁定的对象应该被执行,并在数组中添加元素,并且应该显示通知消息(即)一个对象被通知。但在这里,所有三个对象(即sample、sample1、sample2)都会收到通知并在数组中添加元素。我不知道它为什么以这种方式执行。如果我调用了notifyAll方法三次,那么输出应该与上面的格式相同。我希望输出与前一种情况相同(使用arr.notify()方法获得的输出)
在这个问题上谁能帮我一下
# 1 楼答案
第二个输出是正确的。你对这件事的理解是错误的
3个对象正在等待
arr
,而不仅仅是一个。我认为这解释了调用notifyAll
时的输出你可能会问这是从哪里来的
在每个示例、sample1、sample2线程中,
arr
上都有一个同步块获取锁。所以这个块一次只能执行一次,这是您在获取锁时所期望的。但是当你调用wait
时arr
上的锁就被释放了。所以在sample-1释放锁后,sample-2进入同步块从
wait
文档中: