join的作用
join可以让线程排队执行,而join的内部采用wait方法来实现等待。而join的作用是等待线程对象销毁。
public class MyThread extends Thread {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " run start");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "run end");
}
}
public class JoinTest {
public static void main(String[] args) {
MyThread mt = new MyThread();
mt.setName("MyThread");
mt.start();
try {
mt.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " execute");
}
}
join(long time)设置等待时间
public class JoinTest {
public static void main(String[] args) {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
System.out.printf("%s start %d\n", Thread.currentThread().getName(), System.currentTimeMillis());
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.printf("%s end %d\n", Thread.currentThread().getName(), System.currentTimeMillis());
}
});
t1.setName("t1");
t1.start();
try {
t1.join(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.printf("%s start %d\n", Thread.currentThread().getName(), System.currentTimeMillis());
}
}
结果:
t1 start 1541408642457
main start 1541408644457
t1 end 1541408648500
说明:可以发现在join设置的时间到时之后,将会让join的线程等待,让其他的线程执行。也可以看到join到时间将释放锁。
网友评论