书中的例子:
public class TestThreadAlive extends Thread{
public void run(){
for(int i=0;i<10;i++){
printMsg();
}
}
public void printMsg(){
Thread t = Thread.currentThread();
String name = t.getName();
System.out.println("name=" + name);
}
public static void main(String[] args){
TestThreadAlive tt = new TestThreadAlive();
tt.setName("my worker thread");
System.out.println("before start(),tt.isAlive()=" + tt.isAlive());
tt.start();
System.out.println("just after start(),tt.isAlive()="+tt.isAlive());
for(int i=0;i<10;i++){
tt.printMsg();
}
System.out.println("at the end of main(),tt.isAlive()="+tt.isAlive());
}}它说第二次输出tt.isAlive()时,其值一定为:my worker thread;也就是每次运行到第二个tt.isAlive()时,新Thread对象总是存活的.
这是为什么?难道当main函数执行tt.start()后,就不能立即执行新线程,然后再执行main()函数?而非要执行部分main函数线程后,去执行新的线程?
public class TestThreadAlive extends Thread{
public void run(){
for(int i=0;i<10;i++){
printMsg();
}
}
public void printMsg(){
Thread t = Thread.currentThread();
String name = t.getName();
System.out.println("name=" + name);
}
public static void main(String[] args){
TestThreadAlive tt = new TestThreadAlive();
tt.setName("my worker thread");
System.out.println("before start(),tt.isAlive()=" + tt.isAlive());
tt.start();
System.out.println("just after start(),tt.isAlive()="+tt.isAlive());
for(int i=0;i<10;i++){
tt.printMsg();
}
System.out.println("at the end of main(),tt.isAlive()="+tt.isAlive());
}}它说第二次输出tt.isAlive()时,其值一定为:my worker thread;也就是每次运行到第二个tt.isAlive()时,新Thread对象总是存活的.
这是为什么?难道当main函数执行tt.start()后,就不能立即执行新线程,然后再执行main()函数?而非要执行部分main函数线程后,去执行新的线程?
tt.start();
System.out.println("just after start(),tt.isAlive()="+tt.isAlive());--
这一段的输出不是:
before start(),tt.isAlive()=false
just after start(),tt.isAlive()=true
是“运行到第二个tt.isAlive()时,新Thread对象总是存活的.”;
难道当main函数执行tt.start()后,就不能立即执行新线程,然后再执行main()函数?而非要执行部分main函数线程后,去执行新的线程?
----
这是线程同步运行吧,没什么一定的吧。应为主函数连续执行下来的速度太快,所以就直接执行了一段时间,而另外的线程需要一定的切换时间才可以运行。不知说的对不对?
那为什么说第二个tt.isAlive()总是为true呢?
你在前面
加一条
Thread.sleep(40000);
他绝对死掉!
t.setPriority(10)//设置优先级main方法的优先级默认为5