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;
      }
    }
  }
}

解决方案 »

  1.   

    t.start();//---线程t开始启动程序分为两个线程抢系统资源
    -----jvm
           |
           |-主线程:sleep(10000);//主线程睡10秒,也可以理解为主线程等待10杪后再运行
            |
           |-t线程执行run方法,调用线程的start()方法后,会自动调用线程里的run()方法,循环打印当前时间,每打印一次,线程停顿1秒。
    直到10秒后,主线程运行,程序退出。
      

  2.   

    t.start();后,t线程执行run()方法,而主线程执行Thread.sleep(10000)方法,10秒后,执行t.interrupt(); 从而导致run()方法中的循环条件 while(true) 被破坏,循环不再执行,程序结束
      

  3.   

    记住Thread.sleep()挂起的是当前线程就行了。