多线程中的join()方法会影响并发性吗?

时间:2019-04-02 10:59:53

标签: java multithreading

在多线程环境中使用thread.join()方法时,其他线程必须等到当前线程完成执行之后。

有人可以解释一下,它如何影响多线程的性能? 我的意思是,这种join()条件是否真的降低了性能?

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

    Runnable run = () -> System.out.println("Inside run");
    Thread t[] = new Thread[5];
    int i=0;
    while(i<5){
        t[i]= new Thread(run);
        t[i].start();
        t[i].join();
        i++;
    }
}

1 个答案:

答案 0 :(得分:1)

它确实会影响性能,但实际上只有一个线程在调用它。

您的示例的问题是您在循环中调用join。 因此,主线程(运行循环的线程)在第一个线程完成之前不会启动第二个线程。

请考虑以下示例。

Runnable run = () -> {
        //Some computation here, but NO "performance penalty"
        System.out.println("Inside run");
    };
    Thread t[] = new Thread[5];
    int i=0;
    while(i<5){
        t[i]= new Thread(run);
        t[i].start();

        i++;
    }

    while(i<5){
        t[i].join();
    }
    //Some follow-up computation here, but WITH "performance penalty"