join()方法作用

当在主线程当中执行到t1.join()方法时,就认为主线程应该把执行权让给t1

废话不多说看代码:

package com.toov5.thread;

public class JoinThreadTest {

       public static void main(String[] args) {
        
        Thread t1 = new Thread(new Runnable() {
                
                @Override
                public void run() {
                    for(int i=0;i<10;i++){
                        try {
                            Thread.sleep(1000);
                        } catch (Exception e) {
                            // TODO: handle exception
                        }
                        System.out.println(Thread.currentThread().getName()+"i"+i);
                    }
                    
                }
            });
        t1.start();
        
        //主线程在此调用t1.join()方法,就认为主线程应该把执行权交给t1 让t1执行完毕后再执行主线程
        try {
            t1.join();
        } catch (InterruptedException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
//        t1.start();
        
        for(int i=0; i<10;i++){
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
             System.out.println("main"+"i"+i); 
        }
       
    }
    
    
}

如果先调用join的方法在执行 启动线程

package com.toov5.thread;

public class JoinThreadTest {

       public static void main(String[] args) {
        
        Thread t1 = new Thread(new Runnable() {
                
                @Override
                public void run() {
                    for(int i=0;i<10;i++){
                        try {
                            Thread.sleep(1000);
                        } catch (Exception e) {
                            // TODO: handle exception
                        }
                        System.out.println(Thread.currentThread().getName()+"i"+i);
                    }
                    
                }
            });
//        t1.start();
        
        //主线程在此调用t1.join()方法,就认为主线程应该把执行权交给t1 让t1执行完毕后再执行主线程
        try {
            t1.join();
        } catch (InterruptedException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        t1.start();
        
        for(int i=0; i<10;i++){
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
             System.out.println("main"+"i"+i); 
        }
       
    }
    
    
}

结果分别:

猜你喜欢

转载自www.cnblogs.com/toov5/p/9826492.html