public class Test4  implements Runnable{ @Override
public void run() {

for(int i=0;i<10;i++){
System.out.println("A");
if(i==5){
System.out.println(500);
Thread.currentThread().interrupt();
}
}

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

Thread t=new Thread(new Test4());

t.start();

for(int i=0;i<1000;i++){

System.out.println("B");

}
}

}我想当i==5的时候停止线程t可是运行结果是这样的B
B
B
B
B
B
B
B
B
B
A
A
A
A
A
A
stop
A
A
A
A在stop之后t仍然线程存在,就解释怎么才能强制结束线程t

解决方案 »

  1.   

    http://www.cnblogs.com/linjiqin/archive/2011/04/11/2012695.html   lz可以参考这篇帖子!
      

  2.   


    public class Test4 implements Runnable {
    Thread t = null; public void run() { for (int i = 0; i < 10; i++) {
    System.out.println("A");
    if (i == 5) {
    System.out.println(500);
    t.interrupt();
    }
    } } public void info() {
    t = new Thread(new Test4()); t.start(); for (int i = 0; i < 1000; i++) { System.out.println("B"); }
    } public static void main(String[] args) {
    new Test4().info();
    }}
      

  3.   

    interrupt是一种协作机制,http://www.ticmy.com/?p=31就好比是设置了一个标志位,你要自己处理的,比如public void run() {
             
            for(int i=0;i<10;i++){
                System.out.println("A");
                if(i==5){
                    System.out.println(500);
                    //Thread.currentThread().interrupt();
                }
                if(Thread.interrupted()) {
                      throw new InterruptedException("线程被中断");
                }
            }
             
        }
      

  4.   

    想停止线程,让循环结束,退出run()不就行了 ?            if(i==5){
                    System.out.println(500);
                    break;//中断循环,退出run(),线程结束。
                    //Thread.currentThread().interrupt();
                }
      

  5.   

    Thread.currentThread().interrupt(); 并不能马上停止线程,而是通过设置当前线程标记flag
    ,然后调用本地方法去终止,源码: public void interrupt() {
                 if (this != Thread.currentThread())
                     checkAccess();
         
                 synchronized (blockerLock) {
                     Interruptible b = blocker;
                     if (b != null) {
                         interrupt0();           // Just to set the interrupt flag,本地方法
                        b.interrupt(this);
                         return;
                     }
                 }
                 interrupt0();
             }一般可以通过抛出一个InterruptedException异常去强制停止线程。