java - 关于多线程notify的问题
问题描述
public class WaitTest { static class ThreadA extends Thread {public ThreadA(String name){ super(name);}@Overridepublic void run() { synchronized (this){ System.out.println(Thread.currentThread().getName()+' call notify()'); //notify();//notify之后 要等到这个代码块结束之后才会把锁让出去,当然如果在notify之后又有wait,那就会主动把锁让出去 try { System.out.println(Thread.currentThread().getName()+' wait'); //wait(); //Thread.sleep(10000); } catch (Exception e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+' after notify'); }} } public static void main(String[] args) throws InterruptedException {ThreadA t1 =new ThreadA('t1');synchronized (t1){ System.out.println(Thread.currentThread().getName()+' start t1'); t1.start(); System.out.println(Thread.currentThread().getName()+' wait'); t1.wait();////System.out.println(Thread.currentThread().getName()+' notify'); // t1.notify(); System.out.println(t1.getName()); System.out.println(Thread.currentThread().getName()+' continue'); //t1.notify();} }}
照理来说 t1.wait() 应该会阻塞主线程,并没有其他地方notify而去掉t1.start()之后,就能阻塞住了
这是什么道理?编译器优化?还是synchronized代码块内如果不对monitor进行操作,结束主动notify??
问题解答
回答1:并不是优化其实,跟线程的执行有关的。在java doc中,public final synchronized void join(long millis)这个方法的注释上面写着一句话
<p> This implementation uses a loop of {@code this.wait} calls conditioned on {@code this.isAlive}. As a thread terminates the {@code this.notifyAll} method is invoked. It is recommended that applications not use {@code wait}, {@code notify}, or {@code notifyAll} on {@code Thread} instances.
看到加黑体,其实是线程结束之后调用的notifyAll导致wait苏醒的。并不是什么虚拟机优化导致的。希望能解答你的困惑
相关文章:
1. mysql优化 - mysql count(id)查询速度如何优化?2. angular.js - 不适用其他构建工具,怎么搭建angular1项目3. mysql主从 - 请教下mysql 主动-被动模式的双主配置 和 主从配置在应用上有什么区别?4. python - django 里自定义的 login 方法,如何使用 login_required()5. 主从备份 - 跪求mysql 高可用主从方案6. node.js - node_moduls太多了7. java8中,逻辑与 & 符号用在接口类上代表什么意思8. python如何不改动文件的情况下修改文件的 修改日期9. angular.js - Angular路由和express路由的组合使用问题10. python - 关于ACK标志位的TCP端口扫描的疑惑?
