package thread;
public class TestSleep implements Runnable {
private int time = 10;
private Object lock = new Object();
public static void main(String[] args) {
// TODO Auto-generated method stub
TestSleep a = new TestSleep();
Thread t1 = new Thread(a);
Thread t2 = new Thread(a);
t1.start();
t2.start();
}
@Override
public void run() {
// TODO Auto-generated method stub
synchronized (lock) {
for (int i = 0; i < 10; i++) {
try {
if (time == 5)
lock.wait();//Thread.sleep(3000);
//lock.notify();
time--;
System.out.println(Thread.currentThread().getName() + "****" + time);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}运行结果Thread-0****9Thread-0****8Thread-0****7Thread-0****6Thread-0****5按理来说,线程1抢到锁,然后执行,到wait(),释放锁,应该CPU会运行其他线程,为什么运行到这里就停了(没有完全运行完,没有真正停止)
2 回答
慕工程2701759
TA贡献16条经验 获得超17个赞
这个问题我自己知道了,我应该把time--往上面移动到23行,不然time一直等于5导致两个线程一直挂起,那么新的问题来了,线程一被我挂起,线程二应该完全输出,都是线程一还能继续输出。为什么?
添加回答
举报
0/150
提交
取消