import java.util.*;//第一个程序
public class TestInterrupt
{
public static void main(String[] args)
{
MyThread t = new MyThread();
t.start();
try
{
Thread.sleep(10000);//能解释下从t.start();到t.interrupt();的顺序问题吗?
}
catch(InterruptedException e)
{
}
t.interrupt();
}
}
class MyThread extends Thread
{
public void run ()
{
while(true)
{
System.out.println("--"+new Date()+"--");
try
{
sleep(1000);
}
catch(InterruptedException e)
{
return;
}
}
}
}
import java.util.*;//第二个程序
public class TestInterrupt
{
public static void main(String[] args)
{
MyThread t = new MyThread();
t.start();
try
{
t.sleep(10000);//与第一个程序的不同之处,但是结果是相同的
}
catch(InterruptedException e)
{
}
t.interrupt();
}
}
class MyThread extends Thread
{
public void run ()
{
while(true)
{
System.out.println("--"+new Date()+"--");
try
{
sleep(1000);
}
catch(InterruptedException e)
{
return;
}
}
}
}
-----jvm
|
|-主线程:sleep(10000);//主线程睡10秒,也可以理解为主线程等待10杪后再运行
|
|-t线程执行run方法,调用线程的start()方法后,会自动调用线程里的run()方法,循环打印当前时间,每打印一次,线程停顿1秒。
直到10秒后,主线程运行,程序退出。