【问题标题】:How to use the wait() method in java如何在java中使用wait()方法
【发布时间】:2019-04-10 03:01:49
【问题描述】:

为什么 t1 线程 3 秒后无法通知?

    public class MyThread extends Thread{
        public MyThread(String name) {
        super(name);
    }

    //private int ticket = 100;
    public void run() {
        synchronized(this) {
            System.out.println(Thread.currentThread().getName() + " run ");

            while(true)
                ;

        }
    }
}


    public class MultieThreadTest {
        public static void main(String[] args) {
        MyThread t1 = new MyThread("t1");

        synchronized(t1) {
            try {
                System.out.println(Thread.currentThread().getName() + " start t1 ");
                t1.start();

                System.out.println(Thread.currentThread().getName() + " call wait 3000ms");
                t1.wait(3000);

                System.out.println(Thread.currentThread().getName() + " continue ");
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

}

结果是:

主开始 t1

主调用等待 3000ms

t1 运行

但我认为应该是:

主开始 t1

主调用等待 3000ms

t1 运行

//3秒后

主继续

【问题讨论】:

  • 你有两个线程在运行,但它们都在同一个监视器上同步...
  • 您的预期不正确。你打电话给wait(),而不是notify()。您需要阅读 Javadoc。
  • synchronized 应该用在同一个对象上。

标签: java multithreading


【解决方案1】:

t1.wait(3000); 替换为Thread.sleep(3000); 以获得延迟。

Object.wait() 用于挂起方法,直到其他线程在同一对象上调用Object.notify()Object.notifyAll() 以恢复挂起的线程。

参考链接: https://www.baeldung.com/java-wait-notify

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多