62,614
社区成员
发帖
与我相关
我的任务
分享
public class NotifyWaitTest {
public static void main(String[] args) {
Thread c = new Thread(new ThreadC());
c.start();
}
}
class ThreadC implements Runnable {
public void run() {
Thread b = new Thread(new ThreadB());
// 以对象 b 作为锁,这里的对象 b 也就是在 ThreadB 线程中 this 对象
synchronized (b) {
System.out.println("this is threadC");
// 启动 b 线程,由于 b 线程中使用 this,也就是这个 b 对象作为锁,因此 b.start()
// 中的代码并不会马上执行,而需要等待到这个线程将 b 对象锁释放掉
b.start();
System.out.println("Waiting for c to run...");
try {
// 在 b 对象锁上进行等待,等待的同时将 b 锁释放给其他线程用,此时 C 线程在此一直阻塞。
// 当在其他线程中执行了 b.notifyAll() 时会将其唤醒,该线程会等待 b 对象锁重新锁定代码块,
// 执行下面的代码
b.wait();
System.out.println("C has Completed.Now back to main thread");
} catch (InterruptedException e) {
// // 可能在什么地方执行了 Thread.currentThread().interrpt() 方法会抛出此异常
e.printStackTrace();
}
}
}
}
class ThreadB implements Runnable {
@Override
public void run() {
// 使用当前对象作为锁,锁住代码块
// 被锁住的代码只能在 C 线程中释放了 b 对象锁(执行到 b.waite() 方法后),这里才有机会执行,
synchronized (this) {
System.out.println("thread b is waking up");
System.out.println("ThreadB is running..");
// 唤醒所有在这个对象上等待的线程
// 当然了,要其他等待着的线程运行,需要这个线程运行完后释放当前对象锁,其他等待
// 中的线程才有机会重新获得这个对象的锁
notifyAll();
System.out.println("after ThreadB notifyAll");
}
}
}