java---join的含义

来源:互联网 发布:vi编程 编辑:程序博客网 时间:2024/04/30 13:18

java---join的含义:

java的Thread的join()方法,有什么含义呢?一般来说,join是让使用该方法的线程 执行完以后再让别的线程去执行,即使该线程sleep了,那么别的线程也不能执行。要等该线程醒过来接着执行,直到全部执行完后,别的线程才能执行。这就好像我占了一个茅坑拉屎,我拉的时候你当然不能蹲我这个坑,我拉到一半突然想去干点别的事情,比如说去买手纸,在我买手纸的过程中,你还是不能过来拉。直到我买来纸全拉完后,你才能过来拉。

看下面的代码:

class TestThreadMethod extends Thread{
        
public static int shareVar = 0;
        
public TestThreadMethod(String name){
            super(name);
        }

        
public void run(){
            
for(int i=0; i<4; i++){
                System.
out.println(Thread.currentThread().getName() + ":" +  i);
                
try{ Thread.sleep(1000);}
                
catch(InterruptedException e){ }
            }

        }

    }

    
public class TestThread{
        
public static void main(String[] args){
            TestThreadMethod t1 
= new TestThreadMethod("t1");
            TestThreadMethod t2 
= new TestThreadMethod("t2");
            t1.start();
            
try{
                t1.join();}

            
catch(InterruptedException e){}
            t2.start();
        }
 
}

执行结果是:

t1:0
t1:1
t1:2
t1:3
t2:0
t2:1
t2:2
t2:3

 t1没有执行完之前,t2不能执行。

原创粉丝点击