java 线程 线程池 执行异常场景测试

package thread;

import java.lang.Thread.UncaughtExceptionHandler;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;

import com.google.common.util.concurrent.ThreadFactoryBuilder;


/**
 * 线程异常测试
 * @author zzm
 *
 */
public class ThreadTest {
	
	
   public static void main(String[] args) {
	test8();
}
   
   
   
   /**
    * 打印
    */
   public static void test9(){
	   ThreadFactory threadFactory = new ThreadFactoryBuilder()
		        .setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
					public void uncaughtException(Thread t, Throwable e) {
						System.out.println("=="+t.getName()+"e:"+e);
					}
				})
		        .build();
	   java.util.concurrent.ExecutorService executorService= Executors.newSingleThreadExecutor(threadFactory);
	   Future<Object> future = executorService.submit(() -> {
		            throw new RuntimeException("test");
		        });
		
		Object object;
		try {
             //future.get 会触发异常
			 object = future.get();
			 System.out.println("======================"+object);
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		} catch (ExecutionException e1) {
			e1.printStackTrace();
		}
      
   }

   
   /**
    * 打印 future.get(); 会抛出异常,一般要在 线程中处理异常
    */
   public static void test8(){
	   ThreadFactory threadFactory = new ThreadFactoryBuilder()
		        .setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
					public void uncaughtException(Thread t, Throwable e) {
						System.out.println("=="+t.getName()+"e:"+e);
					}
				})
		        .build();
		Future<Object> future = Executors.newSingleThreadExecutor(threadFactory)
		        .submit(() -> {
		            throw new RuntimeException("test");
		        });
		
		Object object;
		try {
             //future.get 会触发异常
			 object = future.get();
			 System.out.println("======================"+object);
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		} catch (ExecutionException e1) {
			e1.printStackTrace();
		}
      
   }

   
   
   /**
    * 打印
    */
   public static void test7(){
	   ThreadFactory threadFactory = new ThreadFactoryBuilder()
		        .setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
					public void uncaughtException(Thread t, Throwable e) {
						System.out.println("=="+t.getName()+"e:"+e);
					}
				})
		        .build();
		Executors.newSingleThreadExecutor(threadFactory)
		        .execute(() -> {
		            throw new RuntimeException("test");
		        });
   }
   
   /**
    * 不打印
    */
   public static void test6(){
	   ThreadFactory threadFactory = new ThreadFactoryBuilder()
		        .setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
					public void uncaughtException(Thread t, Throwable e) {
						System.out.println("=="+t.getName()+"e:"+e);
					}
				})
		        .build();
		Executors.newSingleThreadExecutor(threadFactory)
		        .submit(() -> {
		            throw new RuntimeException("test");
		        });
   }

   
   
   /**
    * 不打日志
    * try {
    result = c.call();
    ran = true;
} catch (Throwable ex) {
    result = null;
    ran = false;
    setException(ex);
}

protected void setException(Throwable t) {
    if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
        outcome = t;
        UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
        finishCompletion();
    }
}
    */
   public static void test5(){
	   Executors.newSingleThreadExecutor().submit(() -> {
		    throw new RuntimeException("My runtime exception");
		});
	   System.out.println("==========================================");
   }

   /**
    * 打日志
    */
   public static void test4(){
	   Executors.newSingleThreadExecutor().execute(() -> {
		    throw new RuntimeException("My runtime exception");
		});
	   System.out.println("==========================================");
   }

   
   
   public static void test3(){
	   Thread t = new Thread(() -> System.out.println(1 / 0));
	   /*t.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
		public void uncaughtException(Thread t, Throwable e) {
			System.out.println("=="+t.getName()+"e:"+e);
		}
	});*/
	   t.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
			public void uncaughtException(Thread t, Throwable e) {
				System.out.println("=="+t.getName()+"e:"+e);
			}
		});
	   
	   t.start();
   }
   
   
   public static void test1(){
	   Thread t = new Thread(() -> System.out.println(1 / 0));
	   t.start();
   }

   
   
   public static void test2(){
	   Thread t = new Thread(() -> {
		    try {
		        System.out.println(1 / 0);
		    } catch (Exception e) {
		       e.printStackTrace();
		    }
		});
		t.start();
		}
   
}
package thread;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;

import org.apache.log4j.Logger;

import com.google.common.collect.Lists;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;

public class ForkJoinPool<T> {

	private final static Logger logger = org.apache.log4j.Logger
			.getLogger(ForkJoinPool.class);

	public static final int AVAILABLE_PROCESSORS_SIZE = Runtime.getRuntime()
			.availableProcessors();

	private ListeningExecutorService executorService = null;

	private ThreadLocal<List<ListenableFuture<T>>> futuresThreadLocal = new ThreadLocal<List<ListenableFuture<T>>>(){
		protected java.util.List<com.google.common.util.concurrent.ListenableFuture<T>> initialValue() {
			 return Lists.newArrayList();
		};
	};

	public ForkJoinPool() {
		this(AVAILABLE_PROCESSORS_SIZE*2);
	}

	public ForkJoinPool(int poolSize) {
		executorService = MoreExecutors
				.listeningDecorator(Executors
						.newFixedThreadPool(poolSize));
	}

	public void createTask() {
	}
	
	
	/**
	 * 
	 * @description
	 * @return ListenableFuture<T>
	 * @Exception
	 */
	public ForkJoinPool<T> addTaskList(final List<Callable<T>> callables) {
		if(callables!=null){
			for(Callable<T> c:callables){
				addTask(c);
			}
		}
		return this;
	}

	/**
	 * 
	 * @description
	 * @return ListenableFuture<T>
	 * @Exception
	 */
	public ForkJoinPool<T> addTask(final Callable<T> callable) {
		ListenableFuture<T> listenableFuture = executorService.submit(callable);
		futuresThreadLocal.get().add(listenableFuture);
		return this;
	}

	/**
	 * 多线程执行商品生成信息
	 * 
	 * @description
	 * @return
	 * @Exception
	 */
	public List<T> executeTask(List<ListenableFuture<T>> futures) {
		long gstartTime = System.currentTimeMillis();
		ListenableFuture<List<T>> successfulQueries = Futures
				.successfulAsList(futures);
		try {
			// 获取所有线程的执行结果
			List<T> lists = successfulQueries.get();
			return lists;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		} 
		logger.info(" executeTask ! cost time:"
				+ (System.currentTimeMillis() - gstartTime));

		return null;
	}
	
	/**
	 * 多线程执行商品生成信息
	 * 
	 * @description
	 * @return
	 * @Exception
	 */
	public List<T> executeTask() {
		List<ListenableFuture<T>> futures = futuresThreadLocal.get();
		try {
			return executeTask(futures);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		} finally {
			futuresThreadLocal.remove();
		}
		return null;
	}
	
	
	
	/**
	 * 拆分任务
	 * 
	 * @param tasks
	 * @param 拆分数量
	 * @return
	 */
	public static <T> List<T> mergeTask(List<List<T>> tasks) {
		if(tasks==null){
			return null;
		}
		List<T> list = Lists.newArrayList();
		for(List<T> l:tasks){
			if(l!=null){
				list.addAll(l);
			}
		}
		return list;
	}

	/**
	 * 拆分任务
	 * 
	 * @param tasks
	 * @param 拆分数量
	 * @return
	 */
	public static <T> List<List<T>> splitTask(List<T> tasks, Integer taskSize) {
		List<List<T>> list = Lists.newArrayList();
        if(tasks==null || taskSize <= 0){
			return list;
		} 
        if(tasks.size() < taskSize){
        	list.add(tasks);
        	return list;
        }
         
        
		int baseNum = tasks.size() / taskSize; // 每个list的最小size
		int remNum = tasks.size() % taskSize; // 得到余数

		int index = 0;
		for (int i = 0; i < taskSize; i++) {
			int arrNum = baseNum; // 每个list对应的size
			if (i < remNum) {
				arrNum += 1;
			}
			List<T> ls = Lists.newArrayList();
			for (int j = index; j < arrNum + index; j++) {
				ls.add(tasks.get(j));
			}
			list.add(ls);
			index += arrNum;
		}
		return list;
	}


	public void shutdown() {
		this.executorService.shutdown();
	}

	
	public static void main(String[] args) {
		//测试线程池内异常情况 guava 线程池,线程执行异常情况下返回null,不会抛出异常
		ForkJoinPool<Object> forkJoinPool = new ForkJoinPool<>(2);
		forkJoinPool.addTask(new Callable<Object>() {
			@Override
			public Object call() throws Exception {
				throw new RuntimeException("test");
			}
		});
		
		forkJoinPool.addTask(new Callable<Object>() {
			@Override
			public Object call() throws Exception {
				return "123";
			}
		});
		List<Object> list = forkJoinPool.executeTask();
		//[null, 123]
		System.out.println(list);
	}
	
}	
	

 

转载于:https://my.oschina.net/xiaominmin/blog/1615929

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值