package WaitingThread;
public class WaitingThread {
public static Object object = new Object();
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
synchronized (object) {
try {
System.out.println(
Thread.currentThread().getName() + "-->获取到锁对象了" + "但是调用了 wait方法,进入到无限等待的方法,释放了锁对象");
object.wait();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("从wait状态醒过来,获取到锁对象,并继续执行了");
}
}
}
}, "等待线程").start();
new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName() + "--> 休眠3秒");
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (object) {
System.out.println(Thread.currentThread().getName() + "获取到了锁对象,调用 了 notify 方法");
object.notify();
}
}
}, "唤醒线程").start();
}
}