如何正确的停止线程

废弃的方法:
  1. Thread.stop
  2. Thread.suspend
  3. Thread.resume
可用的方法:
  1. 标志位
  2. interrupt();
例1    标志位+return
public class C {
    public static void main(String[] args) {
        Thread t = new Thread() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                for (int i = 0; i < 100; i++) {
                    System.out.println("线程" + Thread.currentThread().getName()
                            + ":" + i);
                    if (i == 20) {
                        // break;
                        return;
                    }
                }
            }
 
        };
        t.start();
    }
}
View Code

 

输出:
线程Thread-0:0
线程Thread-0:1
线程Thread-0:2
……
线程Thread-0:20
 
 
例2    标志位+break
public class C {
 
    public static void main(String[] args) {
        Thread t = new Thread() {
 
            private boolean finished;
 
            @Override
            public void run() {
                // TODO Auto-generated method stub
                while (true) {
                    doSomeWork();
                    if (finished) {
                        System.out.println("线程终止");
                        System.err.println("sssssssssss");
                        break;
                    }
                }
            }
 
            private void doSomeWork() {
                System.out.println("doSomeWork");
                finished = true;
            }
        };
        t.start();
    }
}
View Code

 

输出:
doSomeWork
线程终止
sssssssssss
 
 
例3   interrupt()
public class C {
    public static void main(String[] args) {
        Thread t = new Thread() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                for (int i = 0; i < 100; i++) {
                     try{
                         Thread.sleep(1000);
                         if(i==5)
                             Thread.currentThread().interrupt();
                     }catch(InterruptedException e){
                         System.out.println("异常抛出!");
                         throw new RuntimeException();
                     }
                     System.out.println("线程:"+i);
                }
            }
 
        };
        t.start();
    }
}
View Code

 

输出:
线程:0
线程:1
线程:2
线程:3
线程:4
线程:5
异常抛出!
Exception in thread "Thread-0" java.lang.RuntimeException
    at c14.C$1.run(C.java:22)
 
 
 
 
 
 
莫问前程
原文地址:https://www.cnblogs.com/dolphin007/p/4416042.html