今天随便写了一个线程之间相互调度的程序,代码如下:
class First extends Thread { public First() { start(); } synchronized public void run() { try { wait(); } catch(InterruptedException e) { e.printStackTrace(); } try { sleep(2000); } catch(InterruptedException e) { e.printStackTrace(); } System.out.println("hello world~"); } } class Second extends Thread { First first; public Second(First first) { this.first = first; start(); } synchronized public void run() { try { wait(); } catch (InterruptedException e1) { e1.printStackTrace(); } synchronized( first ) { try { sleep(2000); System.out.println("I'm faster than first~"); } catch(InterruptedException e) { e.printStackTrace(); } first.notifyAll(); } } } public class Main { public static void main(String[] args) throws InterruptedException { First first = new First(); Second second = new Second(first); synchronized( second ) { System.out.println("I'm faster than second~"); second.notifyAll(); } } }
本以为输出会很顺畅,但是出现的问题是,只输出了一行:I‘m faster than second~
程序就一直处于无响应状态,纠结了好久终于想明白是这么一回事:在main函数中,对second.notifyAll()的调用早于second中的wait()调用(因为是多线程并行,故函数响应时间与代码先后顺序无关),这样先唤醒了second,紧接着second才开始wait,因此就处于无响应状态。
改进方法:只要在second.notifyAll()调用之前空出一点时间先让second的wait调用开始即可,事实上,这段时间如此之短以至于在我电脑上只需要在之前加一行输出语句即可。为了保险起见,还是多加了个sleep,改进后代码如下:
class First extends Thread { public First() { start(); } synchronized public void run() { try { wait(); } catch(InterruptedException e) { e.printStackTrace(); } try { sleep(2000); } catch(InterruptedException e) { e.printStackTrace(); } System.out.println("hello world~"); } } class Second extends Thread { First first; public Second(First first) { this.first = first; start(); } synchronized public void run() { try { wait(); } catch (InterruptedException e1) { e1.printStackTrace(); } synchronized( first ) { try { sleep(2000); System.out.println("I'm faster than first~"); } catch(InterruptedException e) { e.printStackTrace(); } first.notifyAll(); } } } public class Main { public static void main(String[] args) throws InterruptedException { First first = new First(); Second second = new Second(first); System.out.println("wating for all threads prepared~"); Thread.sleep(2000); synchronized( second ) { System.out.println("I'm faster than second~"); second.notifyAll(); } } }
输出结果:
wating for all threads prepared~
I‘m faster than second~
I‘m faster than first~
hello world~
时间: 2024-10-12 19:21:36