首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >连接()方法在多线程中的工作原理

连接()方法在多线程中的工作原理
EN

Stack Overflow用户
提问于 2019-01-12 14:14:06
回答 2查看 73关注 0票数 0

根据我对join()方法的理解,它允许一个线程等待另一个线程完成。

然后,根据我的代码:线程(t0)一结束,线程(t3)就应该启动,这不会发生

代码语言:javascript
复制
public class Threaded extends Thread {

     @Override
     public void run() {

      for (int i=0; i<5; i++) {

           System.out.println(Thread.currentThread().getName() + ": " + i);

       }

       }

}

public class Demo {

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

        Thread main = Thread.currentThread();

        Threaded t0 = new Threaded();
        Threaded t1 = new Threaded();
        Threaded t2 = new Threaded();
        Threaded t3= new Threaded();

        t0.start();
        t1.start();
        t2.start();

        t0.join();

        t3.start();

    }

}

输出是

代码语言:javascript
复制
main 5  
Thread-1: 0  
Thread-2: 0  
Thread-0: 0  
Thread-2: 1  
Thread-2: 2  
Thread-1: 1  
Thread-2: 3  
Thread-2: 4  
Thread-0: 1  
Thread-0: 2  
Thread-0: 3  
Thread-0: 4  
Thread-1: 2  
Thread-1: 3  
Thread-1: 4  
Thread-3: 0  
Thread-3: 1  
Thread-3: 2  
Thread-3: 3  
Thread-3: 4

在此输出中,线程-3在线程-0、线程-1和线程-2结束后启动.但是,据我所知,线程3在线程0结束时就开始了。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-01-12 15:08:22

Thread.join()等待这个线程死掉。基本上,所有线程都运行在主线程之上。让我试着解释一下你的代码的流程。

代码语言:javascript
复制
public static void main(String[] args) throws InterruptedException {

    Thread main = Thread.currentThread();

    // you have created 4 Thread instances here...
    Threaded t0 = new Threaded();
    Threaded t1 = new Threaded();
    Threaded t2 = new Threaded();
    Threaded t3= new Threaded();

    // you have started t0, t1 and t2 to run on top of main thread
    t0.start();
    t1.start();
    t2.start();

    // here you have used Thread.join()
    // so your main thread will wait here, 
    // it will wait for the completion of t0 
    t0.join();

    // so after the completion of t0, t3 will start
    t3.start();

}

现在,对于您的问题,您的线程t1、t2和t3都位于可运行线程池中。因此,现在选择哪个线程并执行完全掌握在线程调度器的手中。

票数 1
EN

Stack Overflow用户

发布于 2019-01-12 14:18:55

线程-3在线程-0结束后立即启动。

线程-3在线程-0完成后成为可运行的.但这并不意味着它是立即安排的。同时可能有3个可运行的线程,而且先打印哪个线程是不可预测的。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54160399

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档