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();
}
}
}
}
}

最新文章

  1. 使用MyBatis对表执行CRUD操作
  2. 招聘 微软全球技术支持中心 sql server组
  3. 52-which 显示系统命令所在目录
  4. sql之truncate 、delete与drop区别
  5. android自定义控件(3)-自定义当前按钮属性
  6. BTrace入门教程
  7. Android事件分发机制完全解析,带你从源码的角度彻底理解
  8. 【转】12 款优秀的 JavaScript MVC 框架评估
  9. debian修改ip地址
  10. OneAPM x 腾讯 | OneAPM 技术公开课&#183;深圳 报名:前端性能大作战!
  11. MST最小生成树及克鲁斯卡尔(Kruskal)算法
  12. BZOJ 3884 上帝与集合的正确用法
  13. objective c的注释规范
  14. loadrunner学习理论之一
  15. (转)Windows7下命令行使用MySQL
  16. freemarker中的left_pad和right_pad
  17. Lintcode249 Count of Smaller Number before itself solution 题解
  18. [python爬虫]Requests-BeautifulSoup-Re库方案--Requests库介绍
  19. Windows 控制面板调用命令
  20. webpack打包时排除其中一个css、js文件,或单独打包一个css、js文件

热门文章

  1. 排序算法(1) 快速排序 C++实现
  2. VC 6.0 MFC关闭对话框在win7出现崩溃的情况
  3. MVC中使用EF的技巧集(二)——分部验证
  4. apt安装mysql
  5. 枚举类型与位域枚举Enum
  6. mysql 插入汉字异常: Incorrect string value: &#39;\xE8\xB0\xA2\xE9\x9D\x99&#39; for column &#39;uname&#39; at row 1
  7. 【vue.js】入门
  8. spring cloud各个模块作用
  9. vue 路由缓存 路由嵌套 路由守卫 监听物理返回
  10. Docker 常用命令——容器