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