线程死亡的监控与回调


//监控线程是否死亡


package io.mycat.bigmem.util;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicBoolean;


/**
*@desc  监控线程是否死亡,然后执行回调方法.
*@author zhangwy   @date 2017年2月21日 上午6:14:34
**/
public class ThreadDeathWatcher {
	/*started 线程是否已经启动*/
	private static AtomicBoolean started = new AtomicBoolean(false);
	/*需要加入监控,或者不监控的待处理的队列*/
	private static ConcurrentLinkedQueue<Entry> threadQueue = new ConcurrentLinkedQueue<Entry>();
	/*正在处理的线程*/
	private static Thread watchThread = null; 
	/*加入监控*/
	public static void watche(Thread thread,Runnable task) {
		if(thread == null) {
			throw new NullPointerException("thread");
		}
		if(task == null) {
			throw new NullPointerException("task");
		}
		if(!thread.isAlive()) {
			throw new IllegalArgumentException("thread must be alive");
		}
		schedual(thread, task, true);
	} 
	/*移除监控*/
	public static void unWathe(Thread thread, Runnable task) {
		if(thread == null) {
			throw new NullPointerException("thread");
		}
		if(task == null) {
			throw new NullPointerException("task");
		}
		schedual(thread, task, false);
	}
	/*线程任务的调度*/
	private static void schedual(Thread thread, Runnable task, boolean isWatching) {
		Entry entry = new Entry(thread, task, isWatching);
		threadQueue.add(entry);
		if(started.compareAndSet(false, true)) {
			Watcher wathcer = new Watcher();
			watchThread = new Thread(wathcer, "Deather watcher thread");
			watchThread.setDaemon(true);
			watchThread.start();
			System.out.println(watchThread.getName() + " start   ===========");
		}
	}
	
	static final class Watcher implements Runnable {
		List<Entry> watchList = new ArrayList<Entry>();
		/*监控队列,判断线程是否alive,death则从队列中移除,执行回调,*/
		@Override
		public void run() {
			for(;;) { 
				fetchWatchees();
                notifyWatchees();

                fetchWatchees();
                notifyWatchees();
                try {
					Thread.currentThread().sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
                if(watchList.isEmpty() && threadQueue.isEmpty()) {
                	started.compareAndSet(true, false);
                	
                	if(threadQueue.isEmpty()) {
                		/*
                		 * 1.待处理的队列已经为空
                		 * 2.已经启动了新的线程去处理待处理线程了.*/
                		break;
                	}
                	/*1.已经有了待处理的线程了,需要判断是否已经有新的线程已经启动了,如果没有
                	 * 当前线程继续处理,否则让新线程去处理.
                	 * */
                	if(!started.compareAndSet(false, true)) {
                		break;
                	}
                }
			}
		}
		/**
		*@desc
		*@auth zhangwy @date 2017年2月21日 上午7:06:01
		**/
		private void fetchWatchees() {
			for(;;) {
				Entry entry = threadQueue.poll();
				if(entry == null) {
					break;
				}
				if(entry.isWatching) {
					watchList.add(entry);
				} else {
					watchList.remove(entry);
				}
			}
		}
		
		/**
		*@desc
		*@auth zhangwy @date 2017年2月21日 上午7:06:04
		**/
		private void notifyWatchees() {
			for(int i = 0; i < watchList.size(); ) {
				Entry entry = watchList.get(i);
				
				if(!entry.thread.isAlive()) {
					watchList.remove(i);
					try {
						entry.task.run();
					}catch (Exception e) {
						e.printStackTrace();
					}
				} else {
					i++;
				}
			}
		}
	}
}

class Entry {
	Thread thread ;
	Runnable task;
	boolean isWatching;
	
	Entry(Thread thread, Runnable task,boolean isWatching) {
		this.thread = thread;
		this.task = task;
		this.isWatching = isWatching;
	}
	
	/* 
	 * @see java.lang.Object#hashCode()
	 */
	@Override
	public int hashCode() {
		return thread.hashCode() ^ task.hashCode();
	}
	
	/* 
	 * @see java.lang.Object#equals(java.lang.Object)
	 */
	@Override
	public boolean equals(Object obj) {
		if(!(this instanceof Entry)) {
			return false;
		}
		if(!(obj instanceof Entry)) {
			return false;
		}
		Entry entry = (Entry)obj;
		return this.thread == entry.thread && this.task == this.task;
	}
	
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值