在JAVA中,被wait()暂停的线程能否在notifyAll()时获得该线程被暂停的时间?
发布网友
发布时间:2022-05-19 06:49
我来回答
共1个回答
热心网友
时间:2023-10-07 19:36
wait的时候记录时间,再执行的记录下就行了。
public class BaiDuZhiDao6 {
public static void main(String[] args) {
Object lock = new Object();
MyThread1 m1 = new MyThread1();
MyThread2 m2 = new MyThread2();
m1.setLock(lock);
m2.setLock(lock);
m1.start();
m2.start();
}
}
class MyThread1 extends Thread {
private Object lock;
public void setLock(Object lock) {
this.lock = lock;
}
public void run() {
try {
synchronized(lock){
System.out.println("wait开始时间" + System.currentTimeMillis());
lock.wait();
System.out.println("等待结束时间" + System.currentTimeMillis());
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
class MyThread2 extends Thread {
private Object lock;
public void setLock(Object lock) {
this.lock = lock;
}
public void run() {
try {
synchronized(lock){
Thread.sleep(5000);
lock.notifyAll();;
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}