【发布时间】:2016-10-07 23:59:34
【问题描述】:
所以我编写了以下代码来运行一个线程来打印偶数,而另一个线程使用相同的计数器变量来打印奇数。但是,我想知道是什么内部机制导致 notify() 仅在 wait() 之后触发,即使 notify() 在 wait() 之前调用并且之间有操作。
与 T1 一样,发出 notify() 但仅在迭代 10000 次后才进入 wait() 状态。 t2 不应该在 notify 被触发后立即尝试获取锁,或者 notify() 按设计是否等待 wait() 被调用?
PS:我看到无论我将 notify() 调用放在哪里,只要我在 wait() 调用之前编写它,它总是在 wait() 之后调用。
import java.io.IOException;
public class PrintThread implements Runnable {
int i = 0;
private final Object lock = new Object();
public void run() {
synchronized (lock) {
while (i <= 10) {
System.out.println(Thread.currentThread().getName() + " i is " + i);
i++;
lock.notify();
//Just to add some delay
for(int i=0;i<10000;i++){}
try {
lock.wait();
} catch (InterruptedException e) {
System.out.println("Error");
}
}
System.out.println(Thread.currentThread().getName() + " Exiting!");
}
}}
还有驱动程序
public class PrintThreadDriver {
public static void main(String args[]) throws InterruptedException {
PrintThread obj1 = new PrintThread();
Thread t1 = new Thread(obj1);
Thread t2 = new Thread(obj1);
t1.start();
t2.start();
}}
输出:
Thread-0 i is 0
Thread-1 i is 1
Thread-0 i is 2
Thread-1 i is 3
Thread-0 i is 4
Thread-1 i is 5
Thread-0 i is 6
Thread-1 i is 7
Thread-0 i is 8
Thread-1 i is 9
Thread-0 i is 10
Thread-1 Exiting!
我还看到其中一个线程继续处于等待状态。一旦计数器达到 10,关于如何终止它的任何想法?
【问题讨论】:
-
什么错误?它通知正在等待的线程之一。可以有零个或多个。没关系。
-
@EJP 没有错误,只是想知道 notify 是如何不立即调用其他等待线程的。编辑添加更多细节。
-
我指的是你标题中提到的错误。如果这不是您问题的一部分,那是什么意思?
-
@EJP 更正了标题?
-
所以当我问'什么错误'并且你回答'没有错误'时,你真正的意思是'并发访问错误'?为什么不一开始就这么说呢?我现在的问题是您的标题中提到的“这个并发访问错误是什么”?我不知道Java中有这样的事情。您期望它发生的依据是什么?
标签: java multithreading concurrency