从java文档中得出:interrupt是中断线程,为此我做了个试验public class Interrupt {
public static void main(String[] args) {
         Runnable it=new InterruptTest();
         Thread thread=new Thread(it);
         thread.start();
         try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
         thread.interrupt();
}
}
class InterruptTest implements Runnable {
@Override
public void run() {
int i=0;
while(true){
System.out.println(i++);
}
}}按理说2秒应该不打印才对,可是它一直打印个没完?
求高手

解决方案 »

  1.   

    你的try下面的语句就没执行...thread.start()方法执行后就会调用run方法,你的run方法里的while(true)循环是个死循环,会一直执行下去.并且你的thread.interrup()方法是单线程的话就没意义.你可以这样改:public class MyThread extends Thread{
    private boolean stop = false;
    int count=0;
    @Override
    public void run() {
    while (!stop){
    try {
    Thread.sleep(2000);
    count++;
    stop = true;
    System.out.println(count);
    System.out.println("线程终止");
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }

    }

    } public static void main(String[] asrgs) {

    MyThread t = new MyThread();
    t.start();
    }
    }
    多个线程的时候才可以用其他线程来判断另一个线程是否中断
      

  2.   

    while(true) 改成 while(Thread.currentThread().isInterrupted()) 再试试看。
      

  3.   


    写错了,应该改成 while(!Thread.currentThread().isInterrupted()),少了个感叹号,嘿嘿