我不明白如何在线程上使用wait和notify

时间:2015-08-18 20:00:01

标签: java multithreading

我的代码存在问题。我尝试在两个线程中执行两个简单的GUI框架(仅用于测试目的)。我想等待使用wait()的线程并使用notify()notifyAll()通知第二个线程。我还使用过synchronized()但没有用。

任何人都可以非常清楚地(通过一个例子)向我解释我做错了什么吗?我是编程新手,我不太了解它。 谢谢 !

这是我的片段:

public void example5() throws InterruptedException {

    Thread t = new Thread() {
    public final Object obj = new Object();
    public void run() {
          synchronized(this) {   //coordinating activities and data access among multiple threads
                                //The mechanism that Java uses to support synchronization is the monitor
               try {
                obj.wait(3000); //suspendarea thread-ului t / punerea in asteptare

            } catch (InterruptedException ex) {

            }
        JFrame frame  = new JFrame();
        JButton b = new JButton("CLICK ME 1");
        JPanel panel = new JPanel();
        panel.add(b); frame.add(panel); frame.setBounds(700, 500, 150, 100); frame.setVisible(true);
          }
    }
};

        }

Thread t1 = new Thread(new Runnable() {

    public final Object obj = new Object();

        public void run() {
       obj.notify();

        JFrame frame  = new JFrame();
        JButton b = new JButton("CLICK ME 2");
        JPanel panel = new JPanel();
        panel.add(b); frame.add(panel); frame.setBounds(700, 500, 150, 100); frame.setVisible(true);
    }
});

1 个答案:

答案 0 :(得分:1)

等待和通知应该在同一个对象上调用。试试这个:

        Object ob1 = new Object();

    Thread t1 = new Thread() {
        @Override
        public void run() {
            try {
                System.out.println("ob1 tries to wait in t1...");
                synchronized (ob1) {
                    ob1.wait();
                }
                System.out.println("ob1 is up in t1!");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };

    Thread t2 = new Thread() {
        @Override
        public void run() {
            try {
                Thread.sleep(1000);

                System.out.println("t2 tries to notify ob1's single waiter...");
                synchronized (ob1) {
                    ob1.notify();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("t2 notified ob1's single waiter!");
        }
    };

    t1.start();
    t2.start();

输出:

ob1 tries to wait in t1... t2 tries to notify ob1's single waiter... t2 notified ob1's single waiter! ob1 is up in t1!