首页 > 代码库 > 线程流程理解

线程流程理解

1.只要线程thread.start()执行了,程序立刻就多了一个执行的分支。并且这个分支会单独持续的运行下去。

thread.start()后面的代码会继续沿着另一条分支向下执行。

也就是,两条分支,各自持续运行

比如:

public class AppMain {    public static void main(String[] args) throws InterruptedException {        // TODO Auto-generated method stub        long start = System.currentTimeMillis() ;        System.out.println();        ArrayList<Thread> arrayList = new ArrayList<>();        for(int i = 0;i<100;i++)        {            myThread m1 =  new myThread();                    m1.start();                    m1.join();            myThread2 m2 = new myThread2();                    m2.start();                    m2.join();        }        long end = System.currentTimeMillis();        long endure = end-start;        System.out.println("耗时:"+endure);    }}

输出:

Thread-172 :1111 : 111
Thread-173 :2222 : 222
Thread-174 :1111 : 111
Thread-175 :2222 : 222
Thread-176 :1111 : 111
Thread-177 :2222 : 222
Thread-178 :1111 : 111
Thread-179 :2222 : 222
Thread-180 :1111 : 111
Thread-181 :2222 : 222
Thread-182 :1111 : 111
Thread-183 :2222 : 222
Thread-184 :1111 : 111
Thread-185 :2222 : 222
Thread-186 :1111 : 111
Thread-187 :2222 : 222
Thread-188 :1111 : 111
Thread-189 :2222 : 222
Thread-190 :1111 : 111
Thread-191 :2222 : 222
Thread-192 :1111 : 111
Thread-193 :2222 : 222
Thread-194 :1111 : 111
Thread-195 :2222 : 222
Thread-196 :1111 : 111
Thread-197 :2222 : 222
Thread-198 :1111 : 111
Thread-199 :2222 : 222
耗时:68

 

如果不采用join()方法的话,会先执行完main线程,子线程继续执行。则不会正确打印出耗时时间

输出如下:

Thread-181 :2222 : 222
Thread-182 :1111 : 111
Thread-183 :2222 : 222
Thread-184 :1111 : 111
Thread-185 :2222 : 222
Thread-186 :1111 : 111
Thread-187 :2222 : 222
Thread-188 :1111 : 111
Thread-189 :2222 : 222
Thread-190 :1111 : 111

耗时:68----------------------------------会发现主线程先执行完了
Thread-191 :2222 : 222
Thread-192 :1111 : 111
Thread-193 :2222 : 222
Thread-194 :1111 : 111
Thread-195 :2222 : 222
Thread-196 :1111 : 111
Thread-197 :2222 : 222
Thread-198 :1111 : 111
Thread-199 :2222 : 222

线程流程理解