线程超时处理Demo

Main.java

package com.kingson.main;


public class Main {


	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("Begin here...");
		ThreadWathcher wacher = ThreadWathcher.getInstance(10000, 500);
		wacher.start();
		Thread a = new Thread() {


			/*
			 * (non-Javadoc)
			 * 
			 * @see java.lang.Thread#run()
			 */
			@Override
			public void run() {
				// TODO Auto-generated method stub
				super.run();
				int n = 0;
				try {
					while (n < 1000 && !Thread.interrupted()) {


						Thread.sleep(1000);
						n++;
						System.out.println("In thread a..." + n);
					}
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					System.out.println("线程因超时被终止...线程名" + this.getName());
				}


			}


		};
		a.setName("a");
		wacher.register(a);
		a.start();
		Thread b = new Thread() {


			/*
			 * (non-Javadoc)
			 * 
			 * @see java.lang.Thread#run()
			 */
			@Override
			public void run() {
				// TODO Auto-generated method stub
				super.run();
				int n = 0;
				try {
					while (n < 5 && !Thread.interrupted()) {


						Thread.sleep(1000);
						n++;
						System.out.println("In thread b..." + n);
					}
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					System.out.println("线程因超时被终止...线程名" + this.getName());
				}


			}


		};
		b.setName("b");
		b.start();
		wacher.register(b);
		Thread c = new Thread() {


			/*
			 * (non-Javadoc)
			 * 
			 * @see java.lang.Thread#run()
			 */
			@Override
			public void run() {
				// TODO Auto-generated method stub
				super.run();
				int n = 0;
				try {
					while (n < 12 && !Thread.interrupted()) {


						Thread.sleep(1000);
						n++;
						System.out.println("In thread c..." + n);
					}
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					System.out.println("线程因超时被终止...线程名" + this.getName());
				}


			}


		};
		c.setName("c");
		c.start();
		wacher.register(c);
		Thread d = new Thread() {


			/*
			 * (non-Javadoc)
			 * 
			 * @see java.lang.Thread#run()
			 */
			@Override
			public void run() {
				// TODO Auto-generated method stub
				super.run();
				int n = 0;
				try {
					while (n < 15 && !Thread.interrupted()) {


						Thread.sleep(1000);
						n++;
						System.out.println("In thread d..." + n);
					}
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					System.out.println("线程因超时被终止...线程名" + this.getName());
				}


			}


		};
		d.setName("d");
		d.start();
		wacher.register(d);
		System.out.println("Main End...");
	}
}





ThreadWathcher.java

package com.kingson.main;


import java.sql.Time;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Timer;


public class ThreadWathcher extends Thread {


	private static ThreadWathcher watcher;


	private HashMap<Thread, Long> threadBornTimeCollection;
	private ArrayList<Thread> toRemoveThreads;
	private long timeOutMills;
	private long periodMills;


	private ThreadWathcher() {
		this.setDaemon(true);
		threadBornTimeCollection = new HashMap<Thread, Long>();
		toRemoveThreads = new ArrayList<Thread>();
	}


	public static ThreadWathcher getInstance(long timeout, long period) {


		if (watcher == null) {
			watcher = new ThreadWathcher();
			watcher.timeOutMills = timeout;
			watcher.periodMills = period;
		}


		return watcher;
	}


	public int register(Thread thread) {


		threadBornTimeCollection.put(thread, System.currentTimeMillis());


		return threadBornTimeCollection.size();
	}


	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Thread#run()
	 */
	@Override
	public void run() {
		// TODO Auto-generated method stub
		super.run();


		while (true) {// 守护线程
			try {
				Thread.sleep(periodMills);// 每隔periodMills秒检查一次
				System.out.println("Begin check...");
				for (Thread e : threadBornTimeCollection.keySet()) {// 遍历已经注册过超时处理的线程集合
					// System.out.print(threadBornTimeCollection.get(e) + " vs "
					// + System.currentTimeMillis());
					if (Math.abs(threadBornTimeCollection.get(e)
							- System.currentTimeMillis()) > timeOutMills
							&& e.isAlive()) {// 超时
						toRemoveThreads.add(e);// 添加到超時线程集合中
						System.out.println(e.getName() + " 被添加到超时集合中");
					}
				}
				for (Thread e : toRemoveThreads) {// 遍历超时线程集合
					System.out.println("Interrupt thread name:" + e.getName());
					threadBornTimeCollection.remove(e);// 从超时集合中移除
					e.interrupt();// 中断超时线程
				}
				System.out.println("Out removing next clear:");


			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				if (toRemoveThreads.size() > 0) {
					System.out.println("清空超时线程集合");
					toRemoveThreads.clear();// 清空超时线程集合
				}
			}
			// System.out
			// .println("After InterruptedException throws,will execute me?");
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值