public class WaitNotify {
static Object lock = new Object();
static boolean flag = true;
public static void main(String[] args) throws InterruptedException {
Thread waitThread = new Thread(new Wait(), "WaitThread");
waitThread.start();
TimeUnit.SECONDS.sleep(1);
Thread notifyThread = new Thread(new Notify(), "notifyThread");
notifyThread.start();
}
static class Wait implements Runnable {
@Override
public void run() {
synchronized (lock) {
while (flag) {
System.out.println(Thread.currentThread() + "flag is true. wait@" + LocalDateTime.now());
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread() + "flag is false. running@" + LocalDateTime.now());
}
}
}
static class Notify implements Runnable {
@Override
public void run() {
//加锁
synchronized (lock){
System.out.println(Thread.currentThread() + "hold lock. notify@" + LocalDateTime.now());
//获取到lock锁之后,notifyAll,修改flag
lock.notifyAll();
flag = false;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock){
System.out.println(Thread.currentThread() + "hold lock. notify@" + LocalDateTime.now());
try {
Thread.sleep(50000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
static class Notify implements Runnable {
@Override
public void run() {
//加锁
synchronized (lock){
System.out.println(Thread.currentThread() + "hold lock. notify@" + LocalDateTime.now());
//获取到lock锁之后,notifyAll,修改flag
lock.notifyAll();
flag = false;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock){
System.out.println(Thread.currentThread() + "hold lock. notify@" + LocalDateTime.now());
try {
Thread.sleep(50000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}

WaitThread首先获得了对象的锁,然后调用对象的wait()方法,释放锁,进入了等待队列中,线程状态为waiting;NotifyThread获得了对象的锁,并调用对象的notify()方法,将WaitThread从等待队列移到同步队列中,此时WaitThread的状态变为阻塞Blocked,等待NotifyThread执行完之后释放锁之后WaitThread获取到锁之后0从wait()方法返回并继续执行。

1万+

被折叠的 条评论
为什么被折叠?



