http://sunnylocus.iteye.com/blog/538282当一个单线程化的控制台程序因为未捕获的异常终止的时候,程序停止运行,并生了栈追踪,这与典型的程序输出不同,当一个程序发生了异常说明有不稳定的因素存在。如果并发程序中线程失败就没那么容易发现了。栈追踪可能会从控制台输出,但是没有人会去一直在看控制台,并且,当线程失败的时候,应用程序可能看起来仍在工作。就象程序能跑在50个线程池上,也能够跑在49个线程的线程池上,区别在于50个人干的活要比49个人干的活要多的多。 
  导致线程死亡的的最主要的原因是RuntimeException。因为这些异常表明一个程序错误或者不可修复的错误,它们不着顺着栈的调用传递,此时,默认的行为是在控制台打印栈追踪的信息,并终止线程。
  我们举个例子,将奴隶主比作是你写的程序,奴隶比作是线程。假如你是奴隶主,你手下有5名奴隶,你分派他们一项任务去将不断开采来的石头搬到某个地方。如果中途有奴隶逃跑,那么搬运石头的效率就会下降,如果你没有措施发现奴隶逃跑,最后连一个奴隶也没有了,没有人再去搬石头了。当你发现程序有问题,比如程序刚启动的时候处理速度很快,以后越跑越慢,最后完全停止了,你可能不知道问题出在哪儿,其实这都是因为线程泄露引起的。想解决奴隶逃跑问题,不难,给每个奴隶戴上个报警器,一逃跑报警器就给你发信息,告诉哪个奴隶,因为什么原因逃跑了,可以根据需要再增加一名奴隶,让搬石头的奴隶数量始终维持在5名或着将信息记录到文件,便于分析导致线程泄露的原意改进程序。ok,我们用代码说话
1、定义好报警器
- package com.bill99.thread.test;   
-   
- import java.lang.Thread.UncaughtExceptionHandler;   
-   
-   
- public class UEHLogger implements UncaughtExceptionHandler {   
-     public void uncaughtException(Thread t, Throwable e) {   
-         System.out.println(String.format("不好了,有奴隶逃跑了!奴隶姓名:%1$s,编号:%2$s,逃跑原因:%3$s", t.getName(),t.getId(),e.getMessage()));   
-         System.out.println("还剩"+HelotPool.helotPool.getActiveCount()+"个奴隶");   
-     }   
- }  
 package com.bill99.thread.test;
import java.lang.Thread.UncaughtExceptionHandler;
//将泄露的线程信息输出到控制台
public class UEHLogger implements UncaughtExceptionHandler {
	public void uncaughtException(Thread t, Throwable e) {
		System.out.println(String.format("不好了,有奴隶逃跑了!奴隶姓名:%1$s,编号:%2$s,逃跑原因:%3$s", t.getName(),t.getId(),e.getMessage()));
		System.out.println("还剩"+HelotPool.helotPool.getActiveCount()+"个奴隶");
	}
}
  
2、我们先建立一个奴隶工厂,每名奴隶出工厂的时候都会有一个报警器
     
- package com.bill99.thread.test;   
-   
- import java.util.concurrent.ThreadFactory;   
-   
- public class HelotFactory implements ThreadFactory {   
-     private volatile int helotId=0;  
-       
-     public Thread newThread(Runnable r) {   
-         Thread helotThread = new Thread(r);   
-         helotThread.setName("helot-Thread-"+gethelotId());  
-         helotThread.setUncaughtExceptionHandler(new UEHLogger());  
-         return helotThread;   
-     }   
-     private int gethelotId(){   
-         return ++helotId;   
-     }   
- }  
 package com.bill99.thread.test;
import java.util.concurrent.ThreadFactory;
//奴隶制造工厂
public class HelotFactory implements ThreadFactory {
	private volatile int helotId=0;//奴隶编号
	//产生一个新奴隶
	public Thread newThread(Runnable r) {
		Thread helotThread = new Thread(r);
		helotThread.setName("helot-Thread-"+gethelotId());//设置奴隶姓名
		helotThread.setUncaughtExceptionHandler(new UEHLogger());//UEHLogger就是报警器
		return helotThread;
	}
	private int gethelotId(){
		return ++helotId;
	}
}
 3、奴隶逃跑测试,看看是否会触发报警器
- package com.bill99.thread.test;   
-   
- import java.util.concurrent.ThreadFactory;   
-   
- public class HelotEscapeTest {   
-     private ThreadFactory factory = new HelotFactory();   
-     private Thread helotThread = null;   
-        
-     public HelotEscapeTest(){   
-         Runnable task = new Runnable() {   
-             int stoneNum=1;   
-             public void run() {   
-                 while(!Thread.interrupted()){   
-                     System.out.println(helotThread.getName()+" 搬第"+stoneNum+"块石头..");   
-                     stoneNum++;   
-                     try{   
-                         Thread.sleep(500);   
-                     } catch(InterruptedException e){e.printStackTrace();}   
-                     if(stoneNum>100){   
-                         throw new RuntimeException("又饿又累没力气搬石头了");   
-                     }   
-                 }   
-             }   
-         };   
-         helotThread = factory.newThread(task);   
-     }   
-       
-     public void startWork(){   
-         helotThread.start();   
-     }   
-     public static void main(String[] args) {   
-         HelotEscapeTest test = new HelotEscapeTest();   
-         test.startWork();   
-     }   
- }  
 package com.bill99.thread.test;
import java.util.concurrent.ThreadFactory;
//奴隶逃跑测试
public class HelotEscapeTest {
	private ThreadFactory factory = new HelotFactory();
	private Thread helotThread = null;
	
	public HelotEscapeTest(){
		Runnable task = new Runnable() {
			int stoneNum=1;
			public void run() {
				while(!Thread.interrupted()){
					System.out.println(helotThread.getName()+" 搬第"+stoneNum+"块石头..");
					stoneNum++;
					try{
						Thread.sleep(500);
					} catch(InterruptedException e){e.printStackTrace();}
					if(stoneNum>100){
						throw new RuntimeException("又饿又累没力气搬石头了");
					}
				}
			}
		};
		helotThread = factory.newThread(task);
	}
	//开始干活
	public void startWork(){
		helotThread.start();
	}
	public static void main(String[] args) {
		HelotEscapeTest test = new HelotEscapeTest();
		test.startWork();
	}
}
 运行程序后,奴隶在搬完100块石头后不干了,报警器给出提示信息
   不好了,有奴隶逃跑了!奴隶姓名:helot-Thread-1,编号:7,逃跑原因:又饿又累没力气搬石头了
这样我就能找出线程泄露的原因了。如果在线程池中发生了泄露是否也能记录?
4、奴隶池测试
- package com.bill99.thread.test;   
-   
- import java.util.Random;   
- import java.util.concurrent.BlockingQueue;   
- import java.util.concurrent.LinkedBlockingQueue;   
- import java.util.concurrent.ThreadFactory;   
- import java.util.concurrent.ThreadPoolExecutor;   
- import java.util.concurrent.TimeUnit;   
-   
- public class HelotPoolTest {   
-        
-     public static ThreadPoolExecutor helotPool;   
-     private int helotNum= 5;    
-     private Random random = new Random(100);   
-        
-     private BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>();   
-        
-     public HelotPoolTest() {   
-         ThreadFactory factory = new HelotFactory();   
-         helotPool = new ThreadPoolExecutor( helotNum,helotNum,1000,TimeUnit.SECONDS,queue,factory);   
-     }   
-       
-     public void assignTask(){   
-         final int MAX=100;   
-         final int MIN=10;   
-         Runnable task = null;   
-         for(int j=0;j<20;j++){   
-             task = new Runnable() {   
-                 int stoneNum = random.nextInt(MAX - MIN + 1) + MIN;  
-                 public void run() {   
-                     for (int i = 1; i <= stoneNum; i++) {   
-                         System.out.println(Thread.currentThread().getName() + " 搬完"+ i + "块石头");   
-                         if (i == 60) {   
-                             throw new RuntimeException("搬完第60块石头不干了");   
-                         }   
-                         try{   
-                             Thread.sleep(100);  
-                         }catch(InterruptedException e){e.printStackTrace();}   
-                     }   
-                 }   
-             };   
-             queue.add(task);   
-         }   
-     }   
-       
-     public void startWork(){   
-         helotPool.prestartAllCoreThreads();   
-     }   
-     public static void main(String[] args) {   
-         HelotPoolTest pool = new HelotPoolTest();   
-         pool.assignTask();   
-         pool.startWork();   
-     }   
- }  
 package com.bill99.thread.test;
import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class HelotPoolTest {
	
	public static ThreadPoolExecutor helotPool;
	private int helotNum= 5;  //奴隶数
	private Random random = new Random(100);
	
	private BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>();
	
	public HelotPoolTest() {
		ThreadFactory factory = new HelotFactory();
		helotPool = new ThreadPoolExecutor( helotNum,helotNum,1000,TimeUnit.SECONDS,queue,factory);
	}
	//分配任务
	public void assignTask(){
		final int MAX=100;
		final int MIN=10;
		Runnable task = null;
		for(int j=0;j<20;j++){
			task = new Runnable() {
				int stoneNum = random.nextInt(MAX - MIN + 1) + MIN;// 生成10~100范围的随机数
				public void run() {
					for (int i = 1; i <= stoneNum; i++) {
						System.out.println(Thread.currentThread().getName() + " 搬完"+ i + "块石头");
						if (i == 60) {
							throw new RuntimeException("搬完第60块石头不干了");
						}
						try{
							Thread.sleep(100);//休息下
						}catch(InterruptedException e){e.printStackTrace();}
					}
				}
			};
			queue.add(task);
		}
	}
	//开始干活
	public void startWork(){
		helotPool.prestartAllCoreThreads();
	}
	public static void main(String[] args) {
		HelotPoolTest pool = new HelotPoolTest();
		pool.assignTask();
		pool.startWork();
	}
}
 程序启动,用Jprofiler监控,刚启动时会有5名奴隶干活不一会就会有线程退出,最后5个线程全部退,报警器对每个线程退出都能记录到导致线程退出的原因。标准的Executor实现是:
在需求不高时回收空闲的线程,在需求增加时添加新的线程,如果任务抛出了异常,就会用一个全新的工作线程取代出错的那个。
JDK文档是这么说的,不过通过Jprofiler监控只有在5名奴隶全部逃跑,没人干活的时候ThreadPoolExecutor才会生成一个新线程继续搬石头,并不是只要一个线程退出就会马上生成新线程去代替。
Author: orangelizq
email: orangelizq@163.com
	posted on 2013-05-29 16:43 
桔子汁 阅读(630) 
评论(0)  编辑  收藏  所属分类: 
J2SE