Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the use of join in Java

2025-03-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

小编给大家分享一下Java中join有什么用,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

java多线程里的join,从字面意思来看是联合,合并的意思,但如果面试时这么回答,基本上可以断定面试者还没搞懂。join究竟能干什么,今天给出一个最通俗的解释,那就是在多线程环境下实现暂时以单线程执行,或者说在并行执行的环境中实现暂时以串行执行。为了说明这个问题,我们看一段再常见不过的代码,代码内容是,让三个线程分布去打印一段内容

//代码块1

public class TestJoin {

public static void main(String[] args) throws InterruptedException {

Thread t1 = new Thread(new DoSth());

Thread t2 = new Thread(new DoSth());

Thread t3 = new Thread(new DoSth());

t1.start();

t2.start();

t3.start();

System.out.println("主线程执行");

}

}

class DoSth implements Runnable {

@Override

public void run() {

int n = 5;

while (n > 0) {

System.out.println(Thread.currentThread().getName());

try {

Thread.sleep(1);

} catch (InterruptedException e) {

e.printStackTrace();

}

n--;

}

}

}

执行结果如下:

线程1执行

线程2执行

线程3执行

线程2执行

线程3执行

线程1执行

线程2执行

线程3执行

线程2执行

线程3执行

线程2执行

线程3执行

线程1执行

线程1执行

线程1执行

可见三个线程各自并行执行,并无明确的先后顺序。但如果我们在t.start()后面加上这行代码,

//代码块2

t1.start();

t1.join();

看会出现看什么样的结果:

线程1执行

线程1执行

线程1执行

线程1执行

线程1执行

线程2执行

线程3执行

线程3执行

线程2执行

线程3执行

线程2执行

线程3执行

线程2执行

线程3执行

线程2执行

可以看到线程1执行结束之后线程2和3才开始执行,可见在线程1执行过程中,其他线程并未执行,线程1结束后,线程2,线程3开始并行执行,这就印证了前面的结论,即:join的作用是在多线程环境下暂时以单线程执行。明白了这一点,接下来的问题是,这个特性是怎么实现的呢?我们跟到源码:可以看到

//代码块3

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

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report