码迷,mamicode.com
首页 > 编程语言 > 详细

如何正确停止线程

时间:2015-04-11 01:14:33      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:

废弃的方法们:
  1. Thread.stop
  2. Thread.suspend
  3. Thread.resume
  4. Runtime.runFinalizersOnExit
目前来说,终止线程可以通过2种方法:
  1. 标志位
  2. Thread.currentThread().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();
    }
}
输出:
线程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();
    }
}
输出:
doSomeWork
线程终止
sssssssssss
 
 
例3    Thread.currentThread().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();
    }
}
输出:
线程:0
线程:1
线程:2
线程:3
线程:4
线程:5
异常抛出!
Exception in thread "Thread-0" java.lang.RuntimeException
    at c14.C$1.run(C.java:22)
 
 
 
 
 
 

如何正确停止线程

标签:

原文地址:http://www.cnblogs.com/dolphin007/p/4416042.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!