黑马程序员技术交流社区
标题:
大家快来看看这个线程唤醒的问题~奇怪啊奇怪
[打印本页]
作者:
黑色救护车
时间:
2015-4-28 11:19
标题:
大家快来看看这个线程唤醒的问题~奇怪啊奇怪
本帖最后由 黑色救护车 于 2015-4-28 11:33 编辑
大家看下面这个线程唤醒的代码。
package com.heisejiuhuche.exception;
public class InterruptedExceptionTest {
public static void main(String[] args) {
int x = 0;
Test t = new Test();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
t1.start();
t2.start();
while(true) {
if(x == 60) {
t1.interrupt();
t2.interrupt();
break;
}
// System.out.println(Thread.currentThread().getName() + x);
x ++;
}
System.out.println("Main Over...");
}
}
class Test implements Runnable {
private boolean flag = true;
@Override
public synchronized void run() {
while(flag) {
try {
System.out.println(Thread.currentThread().getName() + " wait...");
wait();
} catch(InterruptedException e) {
System.out.println(Thread.currentThread().getName() + "Interrupted....");
flag = false;
}
System.out.println(Thread.currentThread().getName() + " running");
}
}
}
复制代码
奇怪的问题是这样,代码中注释的那一行代码,注释掉之后,打印结果如下:
Main Over...
Thread-0 wait...
Thread-0Interrupted....
Thread-0 running
复制代码
只有1个线程进行了等待,而且是等主线程执行完之后,才执行了等待的代码。。。然后再被唤醒;而另一个线程根本没有执行等待和唤醒。。。
如果将注释的代码加上,打印结果如下:
main0
Thread-0 wait...
Thread-1 wait...
main1
main2
main3
main4
main5
main6
main7
main8
main9
Main Over...
Thread-0Interrupted....
Thread-0 running
Thread-1Interrupted....
Thread-1 running
复制代码
线程等待在主线程执行时也交替执行了,并且两个线程都执行,并被唤醒。。。这个情况。。。真的是搞不懂。。。大家看看是怎么回事呢。。。
作者:
黑色救护车
时间:
2015-4-28 20:26
木有人回答。。。。我顶~ 大家帮我看看啊!:'(
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2