[答傻姑]Thread的jion方法什么用

10:25上午 八月 19, 2008 in category General by nile black

问:Thread的jion方法什么用?

答:请看Javadoc,明确说明:等待线程终止。假如另一个线程中断了当前线程,就会抛出InterruptedException,并且当前线程的终端状态被清除。

示例代码一:

public class TestThread {
   
public static void main(String arg[]) {
        System.
out.println("main started.");
        Thread[] ts =
new Thread[] { new WaitThread(1000), new WaitThread(2000) };
       
for(Thread t : ts)t.start();
       
try {
            ts[0].join();
        }
catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.
out.println("main finished.");
    }
   
static class WaitThread extends Thread {
       
private int wait;
       
public WaitThread(int wait) {
           
this.wait = wait;
            setName(
"Wait" + wait);
        }
       
@Override
        public void run() {
            System.
out.println(getName() + " started ");
           
try {
                Thread.sleep(
wait);
            }
catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.
out.println(getName() + " finished ");
        }
    }
}

运行结果一:

main started.

Wait1000 started

Wait2000 started

Wait1000 finished

main finished.(注意这里的位置,main线程在Wait2000之前结束了)

Wait2000 finished

 

把代码一稍作修改:

ts[0].join();

之后添加一行

ts[1].join();

等待两个线程结束。

运行结果二:

main started.

Wait1000 started

Wait2000 started

Wait1000 finished

Wait2000 finished

main finished.main线程在Wait2000之后结束。)

Comments[0]

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed