栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

代码分析Java中线程的等待与唤醒

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

代码分析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: %dn", this.getName(), i); 
     // i能被4整除时,休眠100毫秒
     if (i%4 == 0)
Thread.sleep(100);
   }
 } catch (InterruptedException e) {
   e.printStackTrace();
 }
      }
    } 
  } 
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/139955.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号