日期:2014-05-20  浏览次数:20893 次

线程问题,求解释.
主线程main退出,新启动线程会不会随着退出,生命周期怎么样?下面代码运行2次,一次是把sleep注释打开,一次是注释掉,比较2次输出结果,求比较结果的解释!

import org.junit.Test;

public class TestThreadX{
    @Test
    public void testThread() {
        // ExecutorService es = Executors.newFixedThreadPool(3);
        new Thread((new Runnable() {
            @Override
            public void run() {
                call();
            }
        })).start();

        try {
            Thread.sleep(1000*3600);
        } catch (InterruptedException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

    }

    void call() {
        for(int i=0;i<100*100*100;i++){
            System.out.println(i+" %%");
        }
    }
}
------最佳解决方案--------------------
 Settings 
------其他解决方案--------------------
主线程结束了,一切就结束了。。。。
------其他解决方案--------------------
只要有其它非后台线程在运行,jvm就不会退出
------其他解决方案--------------------
Thread.sleep(1000*3600);是暂停当前线程,也就是调用该方法的主程序暂停执行。
 new Thread()被启动,没有暂停。call()方法不会停的。

如果要暂停new Thraed()子线程,可以在call方法里添加。
void call() {
        for(int i=0;i<100*100*100;i++){
            System.out.println(i+" %%");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();  //To change body of catch statement use File 
------其他解决方案--------------------
 Settings 
------其他解决方案--------------------
 File Templates.
            }
        }
    }

或者 定义一个变量,Thread th= new THread(); 然后调用线程的方法。th.sleep(3000);

 public void testThread() {
        // ExecutorService es = Executors.newFixedThreadPool(3);