join()方法等待线程死亡。换句话说, 它导致当前正在运行的线程停止执行, 直到与之连接的线程完成其任务为止。
句法:
public void join()throws InterruptedException |
public void join(long milliseconds)throws InterruptedException |
join()方法的示例
class TestJoinMethod1 extends Thread{
public void run(){
for(int i=1;i<=5;i++){
try{
Thread.sleep(500);
}catch(Exception e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[]){
TestJoinMethod1 t1=new TestJoinMethod1();
TestJoinMethod1 t2=new TestJoinMethod1();
TestJoinMethod1 t3=new TestJoinMethod1();
t1.start();
try{
t1.join();
}catch(Exception e){System.out.println(e);}
t2.start();
t3.start();
}
}
立即测试
Output:1
2
3
4
5
1
1
2
2
3
3
4
4
5
5
如上例所示, 当t1完成其任务时, t2和t3开始执行。 |
join(长毫秒)方法的示例
class TestJoinMethod2 extends Thread{
public void run(){
for(int i=1;i<=5;i++){
try{
Thread.sleep(500);
}catch(Exception e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[]){
TestJoinMethod2 t1=new TestJoinMethod2();
TestJoinMethod2 t2=new TestJoinMethod2();
TestJoinMethod2 t3=new TestJoinMethod2();
t1.start();
try{
t1.join(1500);
}catch(Exception e){System.out.println(e);}
t2.start();
t3.start();
}
}
立即测试
Output:1
2
3
1
4
1
2
5
2
3
3
4
4
5
5
在上面的示例中, 当t1完成其任务1500毫秒(3次)后, t2和t3开始执行。 |
getName(), setName(String)和getId()方法:
public String getName() |
public void setName(String name) |
public long getId() |
class TestJoinMethod3 extends Thread{
public void run(){
System.out.println("running...");
}
public static void main(String args[]){
TestJoinMethod3 t1=new TestJoinMethod3();
TestJoinMethod3 t2=new TestJoinMethod3();
System.out.println("Name of t1:"+t1.getName());
System.out.println("Name of t2:"+t2.getName());
System.out.println("id of t1:"+t1.getId());
t1.start();
t2.start();
t1.setName("Sonoo Jaiswal");
System.out.println("After changing name of t1:"+t1.getName());
}
}
立即测试
Output:Name of t1:Thread-0
Name of t2:Thread-1
id of t1:8
running...
After changling name of t1:Sonoo Jaiswal
running...
currentThread()方法:
currentThread()方法返回对当前正在执行的线程对象的引用。 |
句法:
public static Thread currentThread() |
currentThread()方法的示例
class TestJoinMethod4 extends Thread{
public void run(){
System.out.println(Thread.currentThread().getName());
}
}
public static void main(String args[]){
TestJoinMethod4 t1=new TestJoinMethod4();
TestJoinMethod4 t2=new TestJoinMethod4();
t1.start();
t2.start();
}
}
立即测试
Output:Thread-0
Thread-1
评论前必须登录!
注册