Java多线程中join方法的理解

thread.Join把指定的线程加入到当前线程,可以将两个交替执行的线程合并为顺序执行的线程。比如在线程B中调用了线程A的Join()方法,直到线程A执行完毕后,才会继续执行线程B。
//例如
t.join(); //使调用线程 t 在此之前执行完毕。
t.join(1000); //等待 t 线程,等待时间是1000毫秒
下面通过一个例子介绍一下

public class ConcurrencyTest {
    private static final long count = 1000000000l;
    public static void main(String[] args) throws InterruptedException {
        concurrency();
    }
    private static void concurrency() throws InterruptedException {
        long start = System.currentTimeMillis();
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                int a = 0;
                for (long i = 0; i < count; i++) {
                    a += 5;
                }
                System.out.println("thread finish");
            }
        });
        thread.start();
        int b = 0;
        for (long i = 0; i < count; i++) {
            b--;
        }
        long time = System.currentTimeMillis() - start;
        thread.join();
        System.out.println("finish");
        System.out.println("concurrency :" + time+"ms,b="+b);
    }
}

上述代码中我们将thread join 到concurrency 方法中查看结果
这里写图片描述
发现thread 比 concurrency 先执行完成
我们注释掉 thread.join();

public class ConcurrencyTest {
    private static final long count = 1000000000l;
    public static void main(String[] args) throws InterruptedException {
        concurrency();
    }
    private static void concurrency() throws InterruptedException {
        long start = System.currentTimeMillis();
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                int a = 0;
                for (long i = 0; i < count; i++) {
                    a += 5;
                }
                System.out.println("thread finish");
            }
        });
        thread.start();
        int b = 0;
        for (long i = 0; i < count; i++) {
            b--;
        }
        long time = System.currentTimeMillis() - start;
        //thread.join();
        System.out.println("finish");
        System.out.println("concurrency :" + time+"ms,b="+b);
    }
}

执行程序 查看结果
这里写图片描述
发现 concurrency 优先于 thread 执行完成 并且 执行时间少于 join 的时间
文章地址 :http://www.haha174.top/article/details/255856

你可能感兴趣的:(java,多线程,java,多线程)