前言
现在面试中,不光会问力扣之类的算法,手撕多线程问题也被提上了日程。多线程之间的顺序执行是一个高频的面试手撕题,而且在实际应用中也会有用武之地。因此在这里,我们考虑使用不同的方式来实现多线程的顺序执行。在本文中,我们采用了syncronize,ReentrantLock,join等方式来实现顺序执行。
方法实现
syncronize配合wait/notify
本方法采用sync提供的锁机制配合等待通知来实现多线程的顺序执行。具体代码如下:
public class ExcuteOrder {private final Object lock=new Object();private int current=1;public static void main(String[] args) {ExcuteOrder excuteOrder = new ExcuteOrder();excuteOrder.printOrder();}public void printOrder(){new Thread(()->printNums(3)).start();new Thread(()->printChars(2)).start();new Thread(()->printCH(1)).start();}public void printNums(int orderNum){synchronized (lock){while (orderNum!=current) {try {lock.wait();} catch (InterruptedException e) {throw new RuntimeException(e);}}for(int i=1;i<=3;i++){System.out.print(i);}current++;lock.notifyAll();}}public void printChars(int orderNum){synchronized (lock){while (orderNum!=current){try {lock.wait();} catch (InterruptedException e) {throw new RuntimeException(e);}}for(char i='A';i<='C';i++){System.out.print(i);}current++;lock.notifyAll();}}public void printCH(int orderNum){synchronized (lock){while (orderNum!=current){try {lock.wait();} catch (InterruptedException e) {throw new RuntimeException(e);}}System.out.print("你好");current++;lock.notifyAll();}}
}
此处设计的方法中传入一个执行编号,与成员变量进行比较,可以使得这几个线程以我们想执行的任意顺序来执行。
lock-condition配合await/signal
设计思路与上面类似,但是使用的是JDK提供的ReentrantLock,相较于sync,它能够提供更灵活的等待条件,并且它的等待通知机制更为灵活,从功能上也可以实现多线程的顺序执行。具体实现代码如下:
public class LockConditionFlow {private int currentNums=1;private ReentrantLock lock=new ReentrantLock();private Condition condition=lock.newCondition();public static void main(String[] args) {LockConditionFlow lockConditionFlow = new LockConditionFlow();lockConditionFlow.printFlow();}public void printFlow(){new Thread(()->printNums(1)).start();new Thread(()->printChars(2)).start();new Thread(()->printChinese(3)).start();}public void printNums(int excuNum){lock.lock();while (excuNum!=currentNums){try {condition.await();} catch (InterruptedException e) {throw new RuntimeException(e);}}for(int i=1;i<=3;i++){System.out.print(i);}currentNums++;condition.signalAll();lock.unlock();}public void printChars(int excuNums){lock.lock();while (excuNums!=currentNums){try {condition.await();} catch (InterruptedException e) {throw new RuntimeException(e);}}for(char i='A';i<='C';i++){System.out.print(i);}currentNums++;condition.signal();lock.unlock();}public void printChinese(int excuNums){lock.lock();while (excuNums!=currentNums){try {condition.await();} catch (InterruptedException e) {throw new RuntimeException(e);}}System.out.print("你好");currentNums++;condition.signalAll();lock.unlock();}
}
join
join的使用相对较简单,它会阻塞调用此方法的线程,并等待上一个线程执行结束才能执行,具体实现代码如下:
public class PrintFlowJoin {public static void main(String[] args) {PrintFlowJoin printFlowJoin = new PrintFlowJoin();printFlowJoin.print();}public void print(){Thread thread1 = new Thread(this::printNums);Thread thread2 = new Thread(() -> {try {thread1.join();} catch (InterruptedException e) {throw new RuntimeException(e);}printChars();});Thread thread3 = new Thread(() -> {try {thread2.join();} catch (InterruptedException e) {throw new RuntimeException(e);}printChinese();});thread1.start();thread2.start();thread3.start();}public void printNums(){for(int i=1;i<=3;i++){System.out.print(i);}}public void printChars(){for(char i='A';i<='C';i++){System.out.print(i);}}public void printChinese(){System.out.print("你好");}
}
CountDownLatch
它的思想在于等待countDownLatch的计数器置为零之后唤醒等待在该countDownLatch上的线程,比较适用于多个线程等待某个线程执行完毕之后再执行,类似于一种并行的思想,当然也可以用来实现多个线程的顺序执行,具体代码如下:
public class ExcuteCountDown {public static void main(String[] args) {ExcuteCountDown excuteCountDown = new ExcuteCountDown();excuteCountDown.excute();}public void excute(){CountDownLatch countDownLatch1 = new CountDownLatch(1);CountDownLatch countDownLatch2 = new CountDownLatch(1);Thread thread1 = new Thread(() -> {countDownLatch1.countDown();System.out.println("Thread1");});Thread thread2 = new Thread(() -> {try {countDownLatch1.await();System.out.println("Thread2");countDownLatch2.countDown();} catch (InterruptedException e) {throw new RuntimeException(e);}});Thread thread3 = new Thread(() -> {try {countDownLatch2.await();System.out.println("Thread3");} catch (InterruptedException e) {throw new RuntimeException(e);}});thread1.start();thread2.start();thread3.start();}
}
总结
这几种方案都可以来实现线程的顺序执行,但是它们也有一些区别。sync的方法实现起来比较简单,但是需要手动等待和通知容易造成死锁;而lock-condition的方式提供了更为灵活的等待通知机制,并且可以提供多个condition,所以灵活性很高,但是需要对lock-condition的使用很熟徐;join方法使用也非常简单,只能实现一些简单场景的线程顺序执行;最后是CountDownLatch,它比较适合更为复杂的线程协作场景。