前言
楼主今天在面经上看到这个题,挺有意思,小小的题目对多线程的考量还挺多。大部分同学都会使用 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

这篇博客分享了如何在Java面试中解答关于多线程交替执行,一个线程输出偶数,一个线程输出奇数的问题。文章介绍了三种实现方法:synchronized、CAS以及volatile,并解释了为何使用volatile可以优化性能,同时指出使用非原子操作的隐患。最后,博主还提供了一个翻转字符串的面试小彩蛋。
最低0.47元/天 解锁文章
3783

被折叠的 条评论
为什么被折叠?



