Java Object 对象的 wait() 和 notify()、notifyAll()

0
(0)

在一个线程中通过一个对象来获得锁,调用wait()函数,线程进入阻塞状态。

另一个线程通过也锁定此对象,调用对象的notify()方法通知其中给一个调用wait的对象结束等待状态。如果是调用notifyAll()通知的是前面所有调用此对象wait()方法的线程继续执行。

测试代码:

public class ObjectNotifyTestMain {
    public static void main(String[] args) {
        testNotify();
        testNotifyAll();
    }

    private static void testNotifyAll() {
        Object obj = new Object();
        Thread thread1 = new Thread(() -> {
            synchronized (obj) {
                try {
                    System.out.println(Thread.currentThread().getName() + " - start");
                    obj.wait();
                    System.out.println(Thread.currentThread().getName() + " - resume");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        Thread thread2 = new Thread(() -> {
            synchronized (obj) {
                try {
                    System.out.println(Thread.currentThread().getName() + " - start");
                    obj.wait();
                    System.out.println(Thread.currentThread().getName() + " - resume");

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread1.start();
        thread2.start();
        try {
            Thread.sleep(100);
            synchronized (obj) {
                obj.notifyAll();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static void testNotify() {
        Object obj = new Object();
        Thread thread1 = new Thread(() -> {
            synchronized (obj) {
                try {
                    System.out.println(Thread.currentThread().getName() + " - start");
                    obj.wait();
                    System.out.println(Thread.currentThread().getName() + " - resume");
                    obj.notify();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        Thread thread2 = new Thread(() -> {
            synchronized (obj) {
                System.out.println(Thread.currentThread().getName() + " - start");
                obj.notify();
                try {
                    obj.wait();
                    System.out.println(Thread.currentThread().getName() + " - resume");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });


        thread1.start();
        thread2.start();
    }
}

这篇文章有用吗?

平均评分 0 / 5. 投票数: 0

到目前为止还没有投票!成为第一位评论此文章。

很抱歉,这篇文章对您没有用!

让我们改善这篇文章!

告诉我们我们如何改善这篇文章?

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据