扩展线程池

package com.thread.test;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ExceptionTask {

	public static class DivTask implements Runnable {
		int a, b;

		public DivTask(int a, int b) {
			this.a = a;
			this.b = b;
		}

		@Override
		public void run() {
			double re = a / b;
			System.out.println(re);
		}
	}

	public static void main(String[] args) throws InterruptedException, ExecutionException {
		int cpu = Runtime.getRuntime().availableProcessors();
		ExecutorService es = new ThreadPoolExecutor(cpu, cpu, 0L, TimeUnit.MILLISECONDS,
				new SynchronousQueue());

		for (int i = 0; i < 4; i++) {
			//es.submit(new DivTask(100, i));// 1
			es.execute(new DivTask(100, i));// 2
			/*Future submit = es.submit(new DivTask(100, i));
			submit.get();*/  //3
		}
	}
}
package com.thread.test;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TraceThreadPoolExecutor extends ThreadPoolExecutor {

	public TraceThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
			BlockingQueue workQueue) {
		super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
	}

	@Override
	public void execute(Runnable task) {
		super.execute(wrap(task, clientTrace(), Thread.currentThread().getName()));
	}

	private Exception clientTrace() {
		return new Exception("错误");
	}

	private Runnable wrap(final Runnable task, final Exception clientStack, String clientThreadName) {
		return new Runnable() {

			@Override
			public void run() {
				try {
					task.run();
				} catch (Exception e) {
					clientStack.printStackTrace();
					throw e;
				}
			}
		};
	}

	public static void main(String[] args) {
		TraceThreadPoolExecutor pools = new TraceThreadPoolExecutor(0, Integer.MAX_VALUE, 0L, TimeUnit.SECONDS,
				new SynchronousQueue());

		for (int i = 0; i < 5; i++) {
			pools.execute(new DivTask(100, i));
		}
	}

	public static class DivTask implements Runnable {
		int a, b;

		public DivTask(int a, int b) {
			this.a = a;
			this.b = b;
		}

		@Override
		public void run() {
			double re = a / b;
			System.out.println(re);
		}
	}

}

 

你可能感兴趣的:(扩展线程池)