java线程问题~

来源:百度知道 编辑:UC知道 时间:2024/05/30 18:33:30
程序如下:

package test;

public class ThreadDemo2 {
public static void main(String [] args)
{
TestThread1 t= new TestThread1();
t.start();
while(true)
{
System.out.println(Thread.currentThread().getName()+" main thread is running");
}
}

}
class TestThread1 extends Thread
{

public void run()
{
while(true)
{
System.out.println(Thread.currentThread().getName()+" is running!");
}
}
}

为什么我把线程类TestThread1造成死循环,主线程还会运行啊?
运行结果显示如下:
Thread-0 is running!
Thread-0 is running!
Thread-0 is running!
Thread-0 is running!
main main thread is running
Thread-0 is running!
main main thread is running
Thread-0 is running!
main main thread is running
Thread-0 is running!

你写了线程以后,程序自然按照两个线程来执行,当某一个空闲时就执行另一个,而不是像使用单线程时那样执行完一个以后再执行另一个,因此可以穿插着执行

貌似你把while(true)这个method用了两遍.
如果你把其中一个删除掉或许会好一些.

你的代码错了,改正如下:
public class ThreadDemo2 extends Thread{

public void run(){
while(true){
System.out.println(Thread.currentThread().getName()+" is running!");
}
}
public static void main(String [] args) {
Thread tt=new Thread(new ThreadDemo2());
tt.start();
}
}
有问题可以找我的QQ:737731043