class ThreadDemo1
{
public static void main(String [] args)
{
new TestThread().start();//run();这里已经开启了一个线程,主函数本来就是一个线程,相当于你一共开启了两个线程,如果把for循环变大点就会看见两个线程交替执行
for (int x=0;x<5 ;x++ )// for (int x=0;x<60 ;x++ )
{
System.out.println("main thread is running");
}
/*while (true)
{
System.out.println("main thread is running");
}
*/
}
}
class TestThread extends Thread
{
public void run()
{
for (int x=0;x<5;x++ )//for (int x=0;x<60 ;x++ )
{
System.out.println(Thread.currentThread().getName()+" is running");
}
/*while (true)
{
System.out.println(Thread.currentThread().getName()+" is running");
}
*/
}
}
/*
输出结果:
main thread is running
main thread is running
main thread is running
main thread is running
main thread is running
Thread-0 is running
Thread-0 is running
Thread-0 is running
Thread-0 is running
Thread-0 is running
为什么先输出main thread is running,明明先调用的new TestThread.start()方法啊
求高人指教!!!
*/
程序中总共有两个线程,main和Thread-0线程,现输出main thread is running不一定等于先开启main线程,还与CPU的执行权和执行资格有关系。其实每个程序是看定先执行main线程的,因为他是程序的主入口,JVM调用静态的main方法时就已经开启了main线程。你的输出结果是因为CPU的执行权的切换导致的。不知道楼主有没有明白呢?
多线程执行时,程序不一定按顺序执行啊,谁抢到cpu资源,谁就执行, 我main里的循环次数改成100, run方法里的循环次数改成1,多试几次,可以看到如下结果啊
main thread is running
main thread is running
main thread is running
main thread is running
main thread is running
main thread is running
main thread is running
main thread is running
main thread is running
main thread is running
main thread is running
main thread is running
main thread is running
main thread is running
main thread is running
main thread is running
main thread is running
main thread is running
main thread is running
main thread is running
Thread-0 is running
main thread is running
main thread is running
main thread is running
main thread is running
main thread is running
main thread is running
main thread is running
main thread is running