之前转载的java 多线程 wait() 以及 notirfy() 简析一文,作者关于多线程wait()的论述是对的,但程序有些bug
package com.szn.multithread; public class ThreadA { public static void main(String[] args) { ThreadB b = new ThreadB(); b.start(); System.out.println("b is start...."); synchronized (b)// 括号里的b是什么意思,起什么作用? { try { System.out.println("Waiting for b to complete..."); b.wait();// 这一句是什么意思,究竟让谁wait? System.out.println("Completed.Now back to main thread"); } catch (InterruptedException e) { } } System.out.println("Total is :" + b.total); } } class ThreadB extends Thread { int total; public void run() { synchronized (this) { System.out.println("ThreadB is running.."); for (int i = 0; i < 100; i++) { total += i; } System.out.println("in b, total is " + total); notify(); } } }
//结果1:
//b is start....如果想让程序正确执行,应该保证A线程先获取对象锁,这只需让B线程延时一下
更改后程序:
package com.szn.multithread; public class ThreadA { public static void main(String[] args) { ThreadB b = new ThreadB(); b.start(); System.out.println("b is start...."); synchronized (b)// 括号里的b是什么意思,起什么作用? { try { System.out.println("Waiting for b to complete..."); b.wait();// 这一句是什么意思,究竟让谁wait? System.out.println("Completed.Now back to main thread"); } catch (InterruptedException e) { } } System.out.println("Total is :" + b.total); } } class ThreadB extends Thread { int total; public void run() { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (this) { System.out.println("ThreadB is running.."); for (int i = 0; i < 100; i++) { total += i; } System.out.println("in b, total is " + total); notify(); } } }