主线程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+" %%");
}
}
}
@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+" %%");
}
}
}
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 | Settings | File Templates.
} }
我意思是:
1,在主线程暂停足够长的时间的情况下,能保证子线程执行完,确实输出了100*100*100行
2,在子线程启动,主线程立即结束的情况下,子线程在的输出持续足够长的时间(100*100*100次输出,保证主线程结束了),但是子线程却没有执行完,也就是没有输出100*100*100行.请解释下,第二中情况中的缘由.