停止线程

Reads: 2169 Edit

在Java中有以下3中方法可以种植正在运行的线程。

1 使用退出标志,是线程正常退出,也就是当run方法完成后线程终止。

2 使用stop方法终止线程,不推荐使用这个方法,已经作废过期。

3 使用interupt方法终端线程。

停止不了的线程

本实例将调用interrupt()方法来停止线程,但interrupt()方法的使用效果并不像 for break语句那样,马上停止循环。调用interrupt() 方法仅仅实在当前线程中打了一个停止的标记,并不是真的停止线程。

package com.controller;

public class MyThread2 extends Thread {
	
	public void run() {
		for(int i=0;i< 500;i++) {
			System.out.println("i=" + i);
		}
		
	}
}

package com.controller;

public class Run2 {

	public static void main(String[] args) {
		
		MyThread2 thread = new MyThread2();
		thread.start();
		try {
			Thread.sleep(1);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		thread.interrupt();
		System.out.println("------ main end -------");
	}
}

判断线程是否停止

Thread.java类里提供了两个方法判断线程的状态是不是停止的。

  1. this.interrupted(): 测试当前线程是否已经中断

  2. this.isInterrupted(): 测试线程是否已经中断

this.interrupted() 测试当前线程是否已经中断,当前线程是指运行this.interrupted()方法的线程。

package com.controller;

public class MyThread2 extends Thread {
	
	public void run() {
		for(int i=0;i< 500;i++) {
			System.out.println("i=" + i);
		}
		
	}
}

package com.controller;

public class Run2 {

	public static void main(String[] args) {
		MyThread2 thread = new MyThread2();
		thread.start();
		try {
			Thread.sleep(1);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		thread.interrupt();
		System.out.println("是否停止1 ? =" + thread.interrupted());
		System.out.println("是否停止2 ? =" + thread.interrupted());
		
		System.out.println("------ main end -------");
	}
}

从控制台打印的结果来看,线程并未停止,也就证明了interrupted() 方法的解释:测试当前线程是否已经中断,这个当前线程是main,它从未中断过。

是main线程产生中断效果。

package com.controller;

public class Run3 {

	public static void main(String[] args) {
		Thread.currentThread().interrupt();
		System.out.println("是否停止1 ? =" + Thread.interrupted());
		System.out.println("是否停止2 ? =" + Thread.interrupted());
		System.out.println("--- main end ---");

	}

}

运行结果

是否停止1 ? =true
是否停止2 ? =false
--- main end ---

isInterrupted() 测试线程Thread对象是否已经是中断状态。

package com.controller;

public class Run4 {
	public static void main(String[] args) {
		try {
			MyThread2 thr = new MyThread2();
			thr.start();
			Thread.sleep(1000);
			System.out.println("是否停止1 ? =" + thr.isInterrupted() );
			thr.interrupt();
			
			System.out.println("是否停止ֹ2 ? =" + thr.isInterrupted());
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("--- main end ---");
	}

}

关于作者

王硕,网名信平,十年软件开发经验,业余产品经理,精通Java/Python/Go等,喜欢研究技术,著有《PyQt 5 快速开发与实战》《Python 3.* 全栈开发》,多个业余开源项目托管在GitHub上,欢迎微博交流。


Comments

Make a comment

www.ultrapower.com ,王硕的博客,专注于研究互联网产品和技术,提供中文精品教程。 本网站与其它任何公司及/或商标无任何形式关联或合作。