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()方法啊
求高人指教!!!
*/
复制代码
作者: 刘晶 时间: 2014-5-7 12:02
class ThreadDemo1
{
public static void main(String [] args)
{
new TestThread().start(); //run();<font color="#ff0000">这里已经开启了一个线程,主函数本来就是一个线程,相当于你一共开启了两个线程,</font>
复制代码
作者: 刘晶 时间: 2014-5-7 12:07
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
多线程执行时,程序不一定按顺序执行啊,谁抢到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