面试必问!Java 多线程中两个线程交替执行,一个输出偶数,一个输出奇数

楼主今天在面经上看到这个题,挺有意思,小小的题目对多线程的考量还挺多。大部分同学都会使用 synchronized 来实现。楼主今天带来另外两种优化实现,让你面试的时候,傲视群雄!

第一种 synchronized

class ThreadPrintDemo2 { public static void main(String[] args) { final ThreadPrintDemo2 demo2 = new ThreadPrintDemo2(); Thread t1 = new Thread(demo2::print1); Thread t2 = new Thread(demo2::print2); t1.start(); t2.start(); } public synchronized void print2() { for (int i = 1; i <= 100; i += 2) { System.out.println(i); this.notify(); try { this.wait(); Thread.sleep(100);// 防止打印速度过快导致混乱 } catch (InterruptedException e) { // NO } } } public synchronized void print1() { for (int i = 0; i <= 100; i += 2) { System.out.println(i); this.notify(); try { this.wait(); Thread.sleep(100);// 防止打印速度过快导致混乱 } catch (InterruptedException e) { // NO } } } }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zwxgdj.html