Java多线程中join方法

代码一
public class JoinTest implements Runnable{ 
 
     public void run() { 
        try { 
            System.out.println("Begin sleep"); 
            Thread.sleep(1000); 
           System.out.println("End sleep"); 
        } catch (InterruptedException e) { 
            e.printStackTrace(); 
        } 
 
    } 
 
    public static void main(String[] args) { 
        Thread t = new Thread(new JoinTest()); 
        t.start(); 
        try { 
            t.join(1000); 
            System.out.println("joinFinish"); 
        } catch (InterruptedException e) { 
            e.printStackTrace();      
        } 
    }   
}
运行结果:
Begin sleep
joinFinish
End sleep

代码二:
public class JoinTest2 implements Runnable{ 
 
     public void run() { 
        try { 
            System.out.println("Begin sleep"); 
            Thread.sleep(500); 
           System.out.println("End sleep"); 
        } catch (InterruptedException e) { 
            e.printStackTrace(); 
        } 
 
    } 
 
    public static void main(String[] args) { 
        Thread t = new Thread(new JoinTest2()); 
        t.start(); 
        try { 
            t.join(1000); 
            System.out.println("joinFinish"); 
        } catch (InterruptedException e) { 
            e.printStackTrace();      
        } 
    }   

运行结果:
Begin sleep
End sleep
joinFinish


说明:代码一和代码二结果对比说明main线程只等1000毫秒,不管其他线程什么时候结束.

猜你喜欢

转载自st4024589553.iteye.com/blog/2347582