waitjava的简单介绍

发布时间:2023-01-08

本文目录一览:

1、java线程wait方法
2、java中wait方法怎么条用
3、[java wait的用法](#java wait的用法)
4、java中的sleep和wait的区别

java线程wait方法

wait和notify是用在多线程竞争同一锁资源的情况下使用的。 你这段代码实际是个单线程,这个线程自己把自己阻塞了,自然不可能自己把自己唤醒。 你的意图怎么实现呢?需要加入另外一个线程,下面是我仿照你的意图写的一段代码,供参考下

public class A {
    public A() {
        final A a = this;
        Thread th1 = new Thread() {
            @Override
            public void run() {
                // 一直循环,去尝试着唤醒a
                try {
                    this.sleep(10000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                // 为检查是不是能真正实现唤醒a,等待10000毫秒,此时保证a已经处于等待状态中。
                while (true) {
                    /**
                     * 用notify唤醒的线程必须是持有当前锁对象的线程
                     */
                    synchronized (a) {
                        a.notify();
                    }
                }
            }
        };
        th1.setDaemon(true); // 这句也是必须的,将th1设为守护线程,保证在唤醒a以后,所有活动的线程都为守护线程,jvm能及时退出
        th1.start(); // 和a.run的顺序不可以换
        this.run();
    }
    public static void main(String[] args) {
        new A();
    }
    public void run() {
        /**
         * 这里可以换成这样,直接锁住this就行了
         */
        synchronized (this) {
            try {
                this.wait(); // 阻塞当前的线程
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                System.out.println("1"); // 执行finally
            }
        }
    }
}

java中wait方法怎么条用

wait方法用在 synchronized 方法或者 synchronized 块中。一般在判断语句中,如果某条件被触发,让当前线程 wait 并释放对象的锁。此时可以让其他线程可以对用以对象调用 synchronized 方法。直到调用 notify 或者 notifyAllwait 的线程才有可能执行。所以一般 waitnotify 是成对出现的。

java wait的用法

waitObject 的方法,也就是说可以对任意一个对象调用 wait 方法,调用 wait 方法将会将调用者的线程挂起,直到其他线程调用同一个对象的 notify 方法才会重新激活调用者,例如:

// Thread 1
try {
    obj.wait(); // suspend thread until obj.notify() is called
} catch (InterruptedException e) {
}

java中的sleep和wait的区别

sleep和wait的区别:

  1. sleep 的意思是:睡,睡觉,睡眠。
  2. wait 的意思是:等候,推迟,延缓等待,耽搁,伺候用餐。

拓展资料

sleep的用法

  1. They were exhausted from lack of sleep
    由于缺乏睡眠,他们非常疲惫。
  2. During the car journey, the baby slept
    坐车来的路上,宝宝睡着了。
  3. I think he may be ready for a sleep soon.
    我想他也许很快就要睡一觉了。
  4. I can't get to sleep with all that singing.
    那些歌声搅得我无法入睡。
  5. I didn't lose too much sleep over that investigation.
    我并不太担心那个调查。

wait

  1. I walk to a street corner and wait for the school bus
    我走到街角等校车。
  2. There'll be a car waiting for you
    会有辆汽车等你。
  3. I want to talk to you, but it can wait
    我想和你谈谈,但可以晚点再说。
  4. If you think this all sounds very exciting, just wait until you read the book
    如果你觉得所有这些听起来令人兴奋,那就等着去读这本书吧。
  5. "Wait a minute!" he broke in. "This is not giving her a fair hearing!"
    “等一下,”他插嘴说,“这没有给她一个公平的解释机会!”