有这样的一个面试题:
java如何让线程按照自己指定的顺序执行?
最简单的方式就是使用join。
一、join的作用
当主线程需要等待子线程执行完毕,再继续往下执行时,如果使用sleep(xxx),无法知道子线程执行的确切时间;使用wait、notify\notifyAll需要先获取到子线程run方法的锁,再调用wait,然后当子线程执行完再调用notify\notifyAll。
然而如果使用join,主线程只需要在子线程start方法后,执行子线程的join方法。(假设子线程为t)
t.join();
public final synchronized void join(long millis)throws InterruptedException {long base = System.currentTimeMillis();long now = 0;if (millis < 0) {throw new IllegalArgumentException("timeout value is negative");}if (millis == 0) {while (isAlive()) {wait(0);}} else {while (isAlive()) {long delay = millis - now;if (delay <= 0) {break;}wait(delay);now = System.currentTimeMillis() - base;}}}
public class JoinTest {public static void main(String[] args) {MethodClass methodClass = new MethodClass();Thread threadA = new Thread(new Runnable() {@Overridepublic void run() {synchronized (methodClass){methodClass.methodA();}}},"线程A");Thread threadB = new Thread(new Runnable() {@Overridepublic void run() {synchronized (threadA){try {//线程B拿到线程A的锁,然后睡2sThread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}methodClass.methodB();}}},"线程B");Thread threadC = new Thread(new Runnable() {@Overridepublic void run() {try {threadA.join();} catch (InterruptedException e) {e.printStackTrace();}methodClass.methodC();}},"线程C");threadA.start();threadB.start();threadC.start();}}class MethodClass{public void methodA(){System.out.println(new Date() +"::"+Thread.currentThread().getName()+",哈哈哈哈哈哈");}public void methodB(){System.out.println(new Date()+"::"+Thread.currentThread().getName()+",呵呵呵呵呵呵");}public void methodC(){System.out.println(new Date()+"::"+Thread.currentThread().getName()+",嘿嘿嘿嘿嘿嘿");}}
Mon Feb 01 10:32:18 CST 2021::线程A,哈哈哈哈哈哈Mon Feb 01 10:32:20 CST 2021::线程B,呵呵呵呵呵呵Mon Feb 01 10:32:20 CST 2021::线程C,嘿嘿嘿嘿嘿嘿
通过执行结果可知:join方法拿到的是线程对象的锁
最后修改时间:2021-07-07 17:08:00
文章转载自践行者的脚印,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




