楼主今天在面经上看到这个题,挺有意思,小小的题目对多线程的考量还挺多。大部分同窗都会使用 synchronized 来实现。楼主今天带来另外两种优化实现,让你面试的时候,傲视群雄!java
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 } } } }
经过 synchronized 同步两个方法,每次只能有一个线程进入,每打印一个数,就释放锁,另外一个线程进入,拿到锁,打印,唤醒另外一个线程,而后挂起本身。循环反复,实现了一个最基本的打印功能。面试
但,若是你这么写,面试官确定是不满意的。楼主将介绍一种更好的实现。数组
public class ThreadPrintDemo { static AtomicInteger cxsNum = new AtomicInteger(0); static volatile boolean flag = false; public static void main(String[] args) { Thread t1 = new Thread(() -> { for (; 100 > cxsNum.get(); ) { if (!flag && (cxsNum.get() == 0 || cxsNum.incrementAndGet() % 2 == 0)) { try { Thread.sleep(100);// 防止打印速度过快致使混乱 } catch (InterruptedException e) { //NO } System.out.println(cxsNum.get()); flag = true; } } } ); Thread t2 = new Thread(() -> { for (; 100 > cxsNum.get(); ) { if (flag && (cxsNum.incrementAndGet() % 2 != 0)) { try { Thread.sleep(100);// 防止打印速度过快致使混乱 } catch (InterruptedException e) { //NO } System.out.println(cxsNum.get()); flag = false; } } } ); t1.start(); t2.start(); } }
咱们经过使用 CAS,避免线程的上下文切换,而后呢,使用一个 volatile 的 boolean 变量,保证不会出现可见性问题,记住,这个 flag 必定要是 volatile 的,若是不是,可能你的程序运行起来没问题,但最终必定会出问题,并且面试官会立马鄙视你。多线程
这样就消除了使用 synchronized 致使的上下文切换带来的损耗,性能更好。相信,若是你面试的时候,这么写,面试官确定很满意。性能
但,咱们还有性能更好的。优化
class ThreadPrintDemo3{ static volatile int num = 0; static volatile boolean flag = false; public static void main(String[] args) { Thread t1 = new Thread(() -> { for (; 100 > num; ) { if (!flag && (num == 0 || ++num % 2 == 0)) { try { Thread.sleep(100);// 防止打印速度过快致使混乱 } catch (InterruptedException e) { //NO } System.out.println(num); flag = true; } } } ); Thread t2 = new Thread(() -> { for (; 100 > num; ) { if (flag && (++num % 2 != 0)) { try { Thread.sleep(100);// 防止打印速度过快致使混乱 } catch (InterruptedException e) { //NO } System.out.println(num); flag = false; } } } ); t1.start(); t2.start(); } }
咱们使用 volatile 变量代替 CAS 变量,减轻使用 CAS 的消耗,注意,这里 ++num 不是原子的,但不妨碍,由于有 flag 变量控制。而 num 必须是 volatile 的,若是不是,会致使可见性问题。ui
到这里,若是你面试的时候这么写,那么,offer 就不远啦!哈哈😆!!this
class ReverseDemo { public static void main(String[] args) { String test = "abcdefg"; System.out.println(new StringBuilder(test).reverse()); char[] arr = test.toCharArray(); for (int i = arr.length - 1; i >= 0; i--) { System.out.print(arr[i]); } } }
这个就比较简单了,两种方式,一个是 StringBuilder 的 reverse 方法,一个是转换成数组本身打印。本身转换性能更好,reverse 方法内部步骤更多。线程
好啦,但愿你们面试成功!!code