zoukankan      html  css  js  c++  java
  • Thread 的join方法测试

    java中,Thread类的方法join,其作用是保证调用该方法的线程执行完成之后,才会继续执行后续的步骤,属于线程同步的手段之一

    测试类如下:

    /**
     * 线程的join方法测试
     * 结论:join方法是保证该线程完成了,才会执行后续的步骤
     *
     * @author zhangxz
     * @date 2019-11-17 16:54
     */
    
    public class ThreadJoinTest {
    
        public static void main(String[] args) throws InterruptedException {
    //        withJoin();
    //        withoutJoin();
    
            executeNotInOrder();
    
        }
    
        //start和join两个步骤分开,效果:子线程间交替执行,所有完成之后,再执行主线程
        static void executeNotInOrder() throws InterruptedException {
            List<Thread> list = new ArrayList<>();
            for (int i = 0; i < 20; i++) {
                ThreadA threadA1 = new ThreadA("00" + i);
                threadA1.start();
                list.add(threadA1);
            }
            for (Thread thread : list) {
                thread.join();
            }
    
        }
    
        //没有使用join,主线程和子线程之间,是交替这执行的,先后顺序无法保证
        static void withoutJoin() {
            for (int i = 0; i < 10; i++) {
                ThreadA threadA = new ThreadA("" + i);
                threadA.start();
            }
        }
    
        //在每个子线程start之后,都调用其join方法,则主线程会等待子线程执行完成之后,再继续执行后面的步骤。按照顺序执行的
        static void withJoin() throws InterruptedException {
            for (int i = 0; i < 10; i++) {
                ThreadA threadA = new ThreadA("" + i);
                threadA.start();
                threadA.join();
            }
        }
    
        private static class ThreadA extends Thread {
            public ThreadA(String name) {
                super(name);
            }
    
            public ThreadA() {
            }
    
            @Override
            public void run() {
                System.out.println("I am thread a. " + Thread.currentThread().getName());
            }
        }
    
    }
  • 相关阅读:
    use paramiko to connect remote server and execute command
    protect golang source code
    adjust jedi vim to python2 and python3
    install vim plugin local file offline
    add swap file if you only have 1G RAM
    datatables hyperlink in td
    django rest framework custom json format
    【JAVA基础】网络编程
    【JAVA基础】多线程
    【JAVA基础】String类的概述和使用
  • 原文地址:https://www.cnblogs.com/zhangxuezhi/p/11885617.html
Copyright © 2011-2022 走看看