赞
踩
通常我们会在线程中使用一个标志变量来控制线程的运行,如:
- public class TestCallable implements Runnable {
-
-
- private boolean running = true;
-
- public void stop() {
- this.running = false;
- }
-
- public void run() {
- try {
- BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
- while (running) {
- System.out.println("线程正在运行中...");
- Thread.sleep(20000);
- }
- System.out.println("线程被终止.");
- } catch (IOException e) {
- e.printStackTrace();
- }
-
- }
-
- public static void main(String[] args) {
- try {
- TestCallable callable = new TestCallable();
- Thread th = new Thread(callable);
- th.start();
- Thread.sleep(1000);
- callable.stop();
- System.out.println("已下达终止线程命令。");
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
执行上述代码就能发现,线程阻塞在reader.readLine()时,即使主线程改变了标志变量,但是并不能立即结束子线程,只有等待阻塞被打破,且运行到下一次循环条件判断的时候才能终止。所以在使用这种方法时,应该考虑到阻塞这种情况。当然,如果整个循环内的操作属于同一事务时,这种方法倒很不错。
- public class TestCallable extends Thread {
- BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
-
- public void stopThread() {
- interrupt();
- }
-
- public void run() {
- try {
- BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
- reader.close();
- while (!isInterrupted()) {
- System.out.println("线程正在运行中...");
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。