线程问题,求解释.
主线程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);
Thread th = new Thread((new Runnable() {
@Override
public void run() {
call();
}
}));
th.start();
try {
th.sleep(3000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
Thread.sleep(1000*3600);
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File
[其他解释]
File Templates.
}
}
[其他解释]
要回答的,请先看好,把try{sleep()}catch() 这段代码注释,运行一次,然后打开运行一次,比较输出结果...
我意思是:
1,在主线程暂停足够长的时间的情况下,能保证子线程执行完,确实输出了100*100*100行
2,在子线程启动,主线程立即结束的情况下,子线程在的输出持续足够长的时间(100*100*100次输出,保证主线程结束了),但是子线程却没有执行完,也就是没有输出100*100*100行.
请解释下,第二中情况中的缘由.
