wait方法使"当前线程"进入阻塞(等待)状态.

示例分析:

public class TestWait {
public static void main(String[] args) throws InterruptedException {
Thread t = new MyThread("t1");
synchronized (t){ //main线程持有t对象的锁
System.err.println(Thread.currentThread().getName() + "... start");
t.start(); //t被启动后,t执行run里面的方法会阻塞,因为当前线程main持有t对象的锁 System.err.println(Thread.currentThread().getName() + "... in wait...");
t.wait(2);//当前main线程进入阻塞(等待)状态,并且线程main释放t的锁,然后main等待notify后重新去竞争t的锁然后继续执行. //t对象的锁被释放后,线程t执行run方法的sync会获取到锁然后得到执行,执行完后notify该对象t上面等待的线程main(本例子只有main)
//主线程main被唤醒,然后重新竞争t对象的锁,得到锁后,继续执行end.
System.err.println(Thread.currentThread().getName() + "... end");
}
} static class MyThread extends Thread {
public MyThread(String name) {
super(name);
}
@Override
public void run() {
synchronized (this){
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.err.println(Thread.currentThread().getName() + "_exec.."+i);
} System.err.println(Thread.currentThread().getName() + "_ notify...."); notify();//执行完后notify该对象t上面等待的线程,比如主线程
}
}
}
}

最新文章

  1. xamarin 学习
  2. php性能优化
  3. webapi获取IP的方式
  4. [NOIP2011] 提高组 洛谷P1003 铺地毯
  5. MVC小系列(十五)【MVC+ZTree实现对树的CURD及拖拽操作】
  6. javascript对URL中的参数进行简单加密处理
  7. 【好程序员笔记分享】——iOS开发之纯代码键盘退出
  8. 为什么要选择cdn加速
  9. Determining IP information for eth1... failed; no link present. Check cable? 解决办法
  10. ural 1698. Square Country 5(记忆化搜索)
  11. 关于ThinkPHP中的时间自动填充
  12. jQuery 选择器 prop() 和attr()
  13. JSON 的数据转换格式(DataTable或DataSet) -善良公社项目
  14. facebook marketing(市场营销) API(3)
  15. js 数组随机洗牌
  16. JVM中的垃圾回收算法GC
  17. Vue(十)生命周期
  18. 让.net core 支持静态文件
  19. [转][LoadRunner]LR性能测试结果样例分析
  20. groovy 从jsonList中读取某个字段

热门文章

  1. 虫食算(codevs 1064)
  2. 【HDOJ6312】Game(博弈)
  3. SA模板
  4. gridview读取Excel文件中的数据,并将其导入数据库
  5. HDU 5700 区间交
  6. UVA 3882【dp】【简单数学】
  7. Spring Data Redis配置项有多少(不列举具体,只提供找的方法)
  8. centos、mac的grafana安装和简单使用
  9. struts2 自己定义表单
  10. 【深度探索c++对象模型】Function语义学之虚函数