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);
}
}