0
点赞
收藏
分享

微信扫一扫

你真的理解线程是如何保证执行顺序的问题吗?

浮游图灵 2022-07-13 阅读 32


1.概述

1.我们这里的问题,主要是在同一个主线程当中,如何保证各个线程的执行顺序;
这里我们主要是通过join方法去实现
2.下面我们先对join方法的源码进行解析一下

2.Join方法解析

2.1.概述

1.源码我们调用join方法之后,最终会调用wait(0)(0表示一直等待,直到线程处理结束)
这里注意下,我们一般调用wait之后,需要通过notify或者notifyAll方法去通知已经解锁
这里的join方法中,C++底层实际上已经调用notifyAll我们不做过多了解;

public final void join() throws InterruptedException {
join(0);//调用下面的join方法,下面的方法是一个线程安全的方法,锁住的对象是this 当前执行的对象
}

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;
}
}
}

3.通过join方法实现线程顺序执行案例

3.1.未使用join方法前

code

package com.gaoxinfu.demo.jdk.rt.java.lang.thread;

/**
* @Description:
* @Author: gaoxinfu
* @Date: 2020-05-17 11:38
*/
public class JoinDemo {
public static void main(String[] args) throws InterruptedException {

Thread thread1=new Thread(()->{
System.out.println("thread 1");
});
Thread thread2=new Thread(()->{
System.out.println("thread 2");
});
Thread thread3=new Thread(()->{
System.out.println("thread 3");
});

thread1.start();
thread2.start();
thread3.start();

}
}

执行结果

com.gaoxinfu.demo.jdk.rt.java.lang.thread.JoinDemo
thread 1
thread 3
thread 2

Process finished with exit code 0

会出现执行顺序不一致的情况

3.2.使用join方法后

package com.gaoxinfu.demo.jdk.rt.java.lang.thread;

/**
* @Description:
* @Author: gaoxinfu
* @Date: 2020-05-17 11:38
*/
public class JoinDemo {
public static void main(String[] args) throws InterruptedException {

Thread thread1=new Thread(()->{
System.out.println("thread 1");
});
Thread thread2=new Thread(()->{
System.out.println("thread 2");
});
Thread thread3=new Thread(()->{
System.out.println("thread 3");
});

thread1.start();
thread1.join();
thread2.start();
thread2.join();
thread3.start();

}
}

这里不会出现执行乱序

3.3.执行流程

你真的理解线程是如何保证执行顺序的问题吗?_java


这里注意下synchronized void join锁定的对象是主线程JoinDemo

1.join方法的调用实际上阻塞住了主线程,因此,保证了线程的执行顺序


举报

相关推荐

0 条评论