Java 起多线程执行

[java]
package com.sprucetec.pms.sapp.tools.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.*;

/**
* @Description:
* 使用时, 需要新建实例, 保证线程独立的结果集
* 暂不考虑异步获取结果
* 暂不考虑合并结果集
* 暂不考虑统计信息
* 暂不考虑value延时
* @Author: Jasonote cp houguanqun
* @Date: 2018/1/12
**/
public class AsyncVOHelper {
/**日志信息**/
private static Logger logger = LoggerFactory.getLogger(AsyncVOHelper.class);

/**线程池**/
private static final ExecutorService RUNNER = Executors.newFixedThreadPool(5);
/**结果集**/
private final Map<String, Map<Long, ? extends Serializable>> result = new HashMap<>();
/**thread lever task map**/
private final Map<String, FutureTaskWrapper> wrapperMap = new ConcurrentHashMap<>();
/**
* Exception handler
* Caller can override this
*/
private OurHandler handler;
/** default handler**/
private static final OurHandler defaultHandler = new DefaultHandler();

private AsyncVOHelper(OurHandler handler) {
this.handler = handler;
}

/**
* constructor for default handler
*
* @return
*/
public static AsyncVOHelper newInstance() {
return new AsyncVOHelper(defaultHandler);
}

/**
* constructor for input handler
*
* @param handler
* @return
*/
public static AsyncVOHelper newInstance(OurHandler handler) {
return new AsyncVOHelper(handler);
}

/**
* 初始化任务
*
* @param name 标识
* @param callable 动作
*/
public void initTask(String name, Callable callable) {

FutureTaskWrapper taskWrapper = new FutureTaskWrapper(name, callable);

wrapperMap.put(name, taskWrapper);

init(taskWrapper);
}

private void init(FutureTaskWrapper wrapper) {
RUNNER.submit(wrapper);
}

protected void shutdown() {
throw new UnsupportedOperationException("暂不支持");
}

/**
* 指定key获取 结果
* avoid lining get result.
* To specify the results by the key
*
* @param key
* @return
*/
public Map<Long, ? extends Serializable> getResult(String key) {

long current = System.currentTimeMillis();
FutureTaskWrapper taskWrapper = wrapperMap.get(key);
if (taskWrapper != null) {
try {
return (Map<Long, ? extends Serializable>) taskWrapper.get();
} catch (Exception e) {
handler.handleException(taskWrapper);
} finally {
System.out.println("获取 " + key + " map 耗时 : " + (System.currentTimeMillis() – current) / 1000f);
}
}

/**
* caller can use this to catch Exception
*/
return null;
}

/**
* 线性获取
* easy lining get
*
* @return
*/
public Map<String, Map<Long, ? extends Serializable>> getResult() {

wrapperMap.entrySet().forEach(entry ->
this.process(entry.getKey(), entry.getValue())
);

return result;
}

/**
* 执行
*
* @param key
* @param value
*/
private void process(String key, FutureTaskWrapper value) {
long current = System.currentTimeMillis();
try {
result.put(key, (Map<Long, ? extends Serializable>) value.get());
} catch (Exception e) {
handler.handleException(value);
} finally {
System.out.println("获取 " + key + " map 耗时 : " + (System.currentTimeMillis() – current) / 1000f);
}
}

public OurHandler getHandler() {
return this.handler;
}

public void setHandler(OurHandler handler) {
if (handler == null) {
throw new NullPointerException("指定的handler 为空, 请检查!");
}
this.handler = handler;
}

/**
* FutureTask包装类.
*/
public static class FutureTaskWrapper extends FutureTask {

private final String Id;

public FutureTaskWrapper(String Id, Callable callable) {
super(callable);
this.Id = Id;
}

public FutureTaskWrapper(String Id, Runnable runnable, Object result) {
super(runnable, result);
this.Id = Id;
}

public String getId() {
return Id;
}
}

public interface OurHandler {
void handleException(FutureTaskWrapper taskWrapper);
}

/**
* 默认异常策略
*/
public static class DefaultHandler implements OurHandler {
@Override
public void handleException(FutureTaskWrapper taskWrapper) {
throw new RuntimeException("获取 " + taskWrapper.getId() + " map 时, 异常");
}
}
}

[/java]

使用

[java]
AsyncVOHelper voHelper = AsyncVOHelper.newInstance();

voHelper.initTask("CLASS_INFO", new Callable() {
@Override
public Object call() throws Exception {
return productService.getClass1NameMap();
}
});

Map<String, Map<Long, ? extends Serializable>> resultMap = voHelper.getResult();

logVo.setfClass1Name((String) resultMap.get("CLASS_INFO").get(logVo.getfClass1()));

[/java]

Jason.wang

When you find your talent can't afford to be ambitious, be quiet and study !

You may also like...