public class TestMain { public static void main(String args[]) throws Exception {
Thread t1 = new MyThread("a"); //不用join的时候thread根本没有结束jvm就停掉了 t1.join(); System.out.println("Mian thread is dead!"); } } class MyThread extends Thread { private String name; public MyThread(String name) { super(name); this.name = name; start(); // TODO 自动生成构造函数存根 }
public void run() { System.out.println("Thread "+name+" is runing!"); try { sleep(5000); }catch(InterruptedException e) { e.printStackTrace(); } System.out.println("Thread "+name+" is stopping!"); }}你可以分别把 t1.join();注释和不注释看console输出的结果,就知道join是干什么用的了。附javadoc中的注释: /** * Waits for this thread to die. * * @exception InterruptedException if another thread has interrupted * the current thread. The <i>interrupted status</i> of the * current thread is cleared when this exception is thrown. */ public final void join() throws InterruptedException { join(0); }
public final void join() throws InterruptedException Waits for this thread to die. Throws: InterruptedException - if another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.************************************** 上面是JavaTM 2 Platform Std. Ed. v1.4.0中的API说明。 这个方法是让线程等待被销毁,实际的回收动作由JVM去执行。
void join() Waits for this thread to die. 英文说得很清楚,等到这个线程结束(死去),也就是这个线程执行完以后,再回到调用这个方法的线程中
我的意思是说
join方法是使用wait方法实现的
{
public static void main(String args[]) throws Exception
{
Thread t1 = new MyThread("a");
//不用join的时候thread根本没有结束jvm就停掉了
t1.join();
System.out.println("Mian thread is dead!");
}
}
class MyThread extends Thread
{
private String name;
public MyThread(String name)
{
super(name);
this.name = name;
start();
// TODO 自动生成构造函数存根
}
public void run()
{
System.out.println("Thread "+name+" is runing!");
try
{
sleep(5000);
}catch(InterruptedException e)
{
e.printStackTrace();
}
System.out.println("Thread "+name+" is stopping!");
}}你可以分别把 t1.join();注释和不注释看console输出的结果,就知道join是干什么用的了。附javadoc中的注释:
/**
* Waits for this thread to die.
*
* @exception InterruptedException if another thread has interrupted
* the current thread. The <i>interrupted status</i> of the
* current thread is cleared when this exception is thrown.
*/
public final void join() throws InterruptedException {
join(0);
}
throws InterruptedException
Waits for this thread to die. Throws:
InterruptedException - if another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.**************************************
上面是JavaTM 2 Platform Std. Ed. v1.4.0中的API说明。
这个方法是让线程等待被销毁,实际的回收动作由JVM去执行。
Waits for this thread to die.
英文说得很清楚,等到这个线程结束(死去),也就是这个线程执行完以后,再回到调用这个方法的线程中