java多线程之停止线程

在多线程开发中停止线程是很重要的技术点。停止线程在Java语言中并不像break语句那样干脆,需要一些技巧性的处理。

一、  异常法

采用异常法来停止一个线程,首先我们需要了解一下两个方法的用法:

1、interrupt()方法

public class MyThread extends Thread{
	@Override
	public void run() {
		for (int i = 1; i <= 10000; i++) {
			System.out.println("i="+i);
		}
	}
	public static void main(String[] args)throws Exception {
		MyThread thread=new MyThread();
		thread.start();
		thread.sleep(10);
		thread.interrupt();
	}
}

上面的例子调用interrupt()方法来停止线程,但interrupt()方法的使用效果并不像for+break语句那样,马上就能停止循环。调用interrupt()方法仅仅是在当前线程打了一个停止的标记,并不是真的停止。那么如果停止线程了?我们接着往下面看。

2、判断线程是否是停止状态


1)、  interrupted()

public class MyThread extends Thread{
	@Override
	public void run() {
		for (int i = 1; i <= 10000; i++) {
			System.out.println("i="+i);
		}
	}
	public static void main(String[] args)throws Exception {
		try{
			MyThread thread=new MyThread();
			thread.start();
			thread.sleep(100);
			thread.interrupt();
			System.out.println("线程停止了吗1?--->"+thread.interrupted());
			System.out.println("线程停止了吗2?--->"+thread.interrupted());
		}catch(Exception e){
			e.printStackTrace();
		}
		System.out.println("end");
		
	}
}

从控制台打印的结果来看,线程没有停止,这就是说,interrupted()测试当前线程是否中断,因为这个当前线程就是main,它没有中断过,所以打印的结果是两个false。
如何使main线程产生中断效果了。我们在看下,下面的例子:
public class MyThread{
	public static void main(String[] args){
		Thread.currentThread().interrupt();
		System.out.println("线程停止了吗1?---->"+Thread.interrupted());
		System.out.println("线程停止了吗2?---->"+Thread.interrupted());
		System.out.println("end");
	}
}


从上面的结果来看,interrupted()方法的确判断当前线程是否是停止状态。但是为什么第2个值是false。原来,连续两次调用该方法第一次会清除中断状态后,第二次调用所以返回flase。

2)、  isInterrupted()

public class MyThread extends Thread{
	@Override
	public void run() {
		for (int i = 1; i <= 10000; i++) {
			System.out.println("i="+i);
		}
	}
	public static void main(String[] args){
		try{
			MyThread thread=new MyThread();
			thread.start();
			thread.sleep(10);
			thread.interrupt();
			System.out.println("线程停止了吗1?--->"+thread.isInterrupted());
			System.out.println("线程停止了吗2?--->"+thread.isInterrupted());
		}catch(Exception e){
			e.printStackTrace();
		}
		System.out.println("end");
		
	}
}


从结果看出方法isInterrupted()并未清除,所以打印出了两个true.

3、停止线程

public class MyThread extends Thread{
	@Override
	public void run() {
		for (int i = 1; i <= 10000; i++) {
			if(this.interrupted()){
				System.out.println("线程是停止状态了,我要退出了.");
				break;
			}
			System.out.println("i="+i);
		}
		System.out.println("如果此处还是循环,那么我就会继续执行.线程并没有停止");
	}
	public static void main(String[] args){
		try{
			MyThread thread=new MyThread();
			thread.start();
			thread.sleep(10);
			thread.interrupt();
			System.out.println("end");
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}


如果这么写的话,线程并没有停止。现在我们在修改下代码,也就是所谓的异常法停止线程。

public class MyThread extends Thread{
	@Override
	public void run() {
		try{
			for (int i = 1; i <= 10000; i++) {
				if(this.interrupted()){
					System.out.println("线程是停止状态了,我要退出了.");
					throw new InterruptedException();
				}
				System.out.println("i="+i);
			}
			System.out.println("我被执行了吗?");
		}catch(InterruptedException e){
			System.out.println("---这次线程停了---");
			e.printStackTrace();
		}
	}
	public static void main(String[] args){
		try{
			MyThread thread=new MyThread();
			thread.start();
			thread.sleep(10);
			thread.interrupt();
			System.out.println("end");
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}



二、  在沉睡中停止

如果线程在sleep()状态下停止线程会有什么效果了?
public class MyThread extends Thread{
	@Override
	public void run() {
		try{
			System.out.println("run start");
			Thread.sleep(1000000);
			System.out.println("run end");
		}catch(InterruptedException e){
			System.out.println("sleep被停止,状态:--->"+this.isInterrupted());
			e.printStackTrace();
		}
	}
	public static void main(String[] args){
		try{
			MyThread thread=new MyThread();
			thread.start();
			thread.interrupt();
			thread.sleep(1000);
		}catch(Exception e){
			System.out.println("main catch");
			e.printStackTrace();
		}
	}
}


从结果我们可以看出,在线程睡眠时候停止某一线程,会异常,并且清除停止状态。我们前面异常停止线程,都是先睡眠,在停止线程,与之相反的操作,我写代码的时候需要注意下。

public class MyThread extends Thread{
	@Override
	public void run() {
		try{
			for (int i = 1; i <= 10000; i++) {
				System.out.println("i="+i);
			}
			System.out.println("run start");
			Thread.sleep(1000000);
			System.out.println("run end");
		}catch(InterruptedException e){
			System.out.println("线程被停止了,在sleep,状态:--->"+this.isInterrupted());
			e.printStackTrace();
		}
	}
	public static void main(String[] args){
		try{
			MyThread thread=new MyThread();
			thread.start();
			thread.interrupt();
		}catch(Exception e){
			System.out.println("main catch");
			e.printStackTrace();
		}
	}
}




三、  暴力停止

public class MyThread extends Thread{
	private int i=0;
	@Override
	public void run() {
		try{
			while (true) {
				i++;
				System.out.println("i="+i);
				Thread.sleep(1000);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	public static void main(String[] args){
		try{
			MyThread thread=new MyThread();
			thread.start();
			Thread.sleep(6000);
			thread.stop();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}


stop()方法已经被弃用,如果强制让线程停止,可以会有一些清理工作没得到完成,还有就是对锁定的对象进行了解锁,导致数据不同步的现象,所以开发时候禁止使用该方法去暴力停止线程。

四、  使用return停止线程

public class MyThread extends Thread{
	private int i=0;
	@Override
	public void run() {
		try{
			while (true) {
				i++;
				if(this.interrupted()){
					System.out.println("线程停止了");
					return;
				}
				System.out.println("i="+i);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	public static void main(String[] args){
		try{
			MyThread thread=new MyThread();
			thread.start();
			Thread.sleep(2000);
			thread.interrupt();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}




PS:不过还是建议使用异常法来停止线程,因为在catch块中还可以将异常向上抛,使线程停止事件得到传播。


版权声明:本文为博主原创文章,未经博主允许不得转载。

转载于:https://my.oschina.net/u/1246822/blog/527723

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
解决线程的死掉问题和超时问题特别好使,在Java中,如果需要设定代码执行的最长时间,即超时,可以用Java线程池ExecutorService类配合Future接口来实现。 Future接口是Java标准API的一部分,在java.util.concurrent包中。Future接口是Java线程Future模式的实 现,可以来进行异步计算。 Future模式可以这样来描述:我有一个任务,提交给了Future,Future替我完成这个任务。期间我自己可以去做任何想做的事情。一段时 间之后,我就便可以从Future那儿取出结果。就相当于下了一张订货单,一段时间后可以拿着提订单来提货,这期间可以干别的任何事情。其中Future 接口就是订货单,真正处理订单的是Executor类,它根据Future接口的要求来生产产品。 Future接口提供方法来检测任务是否被执行完,等待任务执行完获得结果,也可以设置任务执行的超时时间。这个设置超时的方法就是实现Java程 序执行超时的关键。 Future接口是一个泛型接口,严格的格式应该是Future,其中V代表了Future执行的任务返回值的类型。 Future接口的方法介绍如下: boolean cancel(boolean mayInterruptIfRunning) 取消任务的执行。参数指定是否立即中断任务执行,或者等等任务结束 boolean isCancelled() 任务是否已经取消,任务正常完成前将其取消,则返回true boolean isDone() 任务是否已经完成。需要注意的是如果任务正常终止、异常或取消,都将返回true V get() throws InterruptedException, ExecutionException 等待任务执行结束,然后获得V类型的结果。InterruptedException 线程被中断异常, ExecutionException任务执行异常,如果任务被取消,还会抛出CancellationException V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException 同上面的get功能一样,多了设置超时时间。参数timeout指定超时时间,uint指定时间的单位,在枚举类TimeUnit中有相关的定义。如果计 算超时,将抛出TimeoutException Future的实现类有java.util.concurrent.FutureTask即 javax.swing.SwingWorker。通常使用FutureTask来处理我们的任务。FutureTask类同时又 实现了Runnable接口,所以可以直接提交给Executor执行。使用FutureTask实现超时执行的代码如附件:FutureTaskAndExcutor.java 不直接构造Future对象,也可以使用ExecutorService.submit方法来获得Future对象,submit方法即支持以 Callable接口类型,也支持Runnable接口作为参数,具有很大的灵活性。使用示例如FutureTaskAndExcutor中的limitDemo2方法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值