温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java中怎么实现线程的等待与唤醒

发布时间:2021-06-12 18:48:33 来源:亿速云 阅读:273 作者:Leah 栏目:编程语言

这篇文章给大家介绍Java中怎么实现线程的等待与唤醒,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

实例代码:

class ThreadA extends Thread{     public ThreadA(String name) {     super(name);   }     public void run() {     synchronized (this) {       System.out.println(Thread.currentThread().getName()+" call notify()");       notify();     }   } } public class WaitTest {   public static void main(String[] args) {     ThreadA t1 = new ThreadA("t1");     synchronized(t1) {       try {         // 启动“线程t1”         System.out.println(Thread.currentThread().getName()+" start t1");         t1.start();           // 主线程等待t1通过notify()唤醒。         System.out.println(Thread.currentThread().getName()+" wait()");         t1.wait();           System.out.println(Thread.currentThread().getName()+" continue");       } catch (InterruptedException e) {         e.printStackTrace();       }     }   } }

输出结果:main start t1 -> main wait() -> t1 call notify() -> main continue

其实调用t1.start(),t1为就绪状态,只是main方法中,t1被main线程锁住了,t1.wait()的时候,让当前线程等待,其实是让main线程等待了,然后释放了t1锁,t1线程执行,打印t1 call notify(),然后唤醒main线程,最后结束;

这里说一下wait()与sleep()的区别,他们的共同点都是让线程休眠,但是wait()会释放对象同步锁,而sleep()不会;下面的代码t1结束之后才会运行t2;能够证实这一点;

public class SleepLockTest{    private static Object obj = new Object();   public static void main(String[] args){      ThreadA t1 = new ThreadA("t1");      ThreadA t2 = new ThreadA("t2");      t1.start();      t2.start();   }    static class ThreadA extends Thread{     public ThreadA(String name){        super(name);      }      public void run(){        synchronized (obj) {         try {           for(int i=0; i <10; i++){              System.out.printf("%s: %d\n", this.getName(), i);              // i能被4整除时,休眠100毫秒             if (i%4 == 0)               Thread.sleep(100);           }         } catch (InterruptedException e) {           e.printStackTrace();         }       }     }    }  }

关于Java中怎么实现线程的等待与唤醒就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI