Groovy多线程
以下代码是博主自己在平时工作中,使用groovy总结的一些多线程样例,博主作为多线程小白,很多东西都还在学习中,欢迎讨论指点~
1. 必包操作
StringBuffer demo = new StringBuffer();
IntStream.range(0, 100).each {
demo.append(it + " ");
}
return PluginResult.ok(demo.toString());
2. 新建线程
id = null;
def thread = Thread.start {
id = Thread.currentThread().getId();
}
thread.join();
return PluginResult.ok(id);
3. 自定义线程池,用于监控线程执行情况
class ThreadPoolExecutorDef extends ThreadPoolExecutor {
ThreadLocal<Long> threadLocal = new ThreadLocal<>();
static CopyOnWriteArrayList logDef = new CopyOnWriteArrayList();
ConcurrentHashMap map = new ConcurrentHashMap();
ThreadPoolExecutorDef(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue)
}
@Override
protected void beforeExecute(Thread t, Runnable r) {
super.beforeExecute(t, r);
map.put(r, System.currentTimeMillis());
threadLocal.set(System.currentTimeMillis());
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
logDef.add(r.toString() + "耗时: " + (System.currentTimeMillis() - map.get(r))/1000 + "s");
super.afterExecute(r, t);
if (t == null && r instanceof Future<?>) {
try {
Object result = ((Future<?>) r).get();
logDef.add("callback :" + result.toString());
} catch (CancellationException cancellationException) {
t = cancellationException;
} catch (ExecutionException executionException) {
t = executionException.getCause();
} catch (InterruptedException interruptedException) {
Thread.currentThread().interrupt();
}
}
if (t != null) {
logDef.add(t);
}
}
@Override
protected void terminated() {
super.terminated();
logDef.add("terminated ... ");
}
}
AtomicInteger count = new AtomicInteger(0);
def queue = new ArrayBlockingQueue<Runnable>(50000);
CountDownLatch countDownLatch = new CountDownLatch(100);
def threadPool = new ThreadPoolExecutorDef(5, 500, 20, TimeUnit.SECONDS, queue);
def startTime = System.currentTimeMillis();
IntStream.range(0, 100).forEach() { i ->
threadPool.execute {
Thread.sleep(50);
count.incrementAndGet();
countDownLatch.countDown();
}
}
countDownLatch.await();
threadPool.shutdown();
def endTime = System.currentTimeMillis();
return PluginResult.ok(["多线程耗时:【" + (endTime - startTime) / 1000 + "s】", "单线程耗时:【5s】", "总计" + count.get() + "次", ThreadPoolExecutorDef.logDef, ThreadPoolExecutorDef.logDef.size()]);
4. future+callable
class FutureTask implements Callable<Map<String, Object>> {
@Override
Map<String, Object> call() throws Exception {
Thread.sleep(500);
return [key: System.currentTimeMillis()];
}
}
def fStartTime = System.currentTimeMillis();
List<Future<Map<String, Object>>> futureList = [];
ExecutorService es = Executors.newCachedThreadPool();
for (int i = 0; i < 100; i++) {
futureList.add(es.submit(new FutureTask()));
}
for (Future<Map<String, Object>> item : futureList) {
item.get();
}
def fEndTime = System.currentTimeMillis();
return PluginResult.ok([costs: (fEndTime - fStartTime) / 1000 + "s", list: futureList]);
5. Semaphore信号量,限制并发访问数
Semaphore semaphore = new Semaphore(3);
CountDownLatch sCountDownLatch = new CountDownLatch(100);
def sQueue = new ArrayBlockingQueue<Runnable>(50000);
def sThreadPool = new ThreadPoolExecutor(5, 500, 20, TimeUnit.SECONDS, sQueue);
def sStartTime = System.currentTimeMillis();
IntStream.range(0, 100).each {
sThreadPool.execute {
semaphore.acquire();
sCountDownLatch.countDown();
Thread.sleep(50);
semaphore.release();
}
}
sCountDownLatch.await();
def sEndTime = System.currentTimeMillis();
sCountDownLatch = new CountDownLatch(100);
IntStream.range(0, 100).each {
sThreadPool.execute {
sCountDownLatch.countDown();
Thread.sleep(50);
}
}
sCountDownLatch.await();
def sEndTime2 = System.currentTimeMillis();
return PluginResult.ok(["信号量(3个并发线程)耗时:【" + (sEndTime - sStartTime) / 1000 + "s】", "线程池耗时:【" + (sEndTime2 - sEndTime) / 1000 + "s】", "单线程耗时:【5s】"]);
6. condition,场景:多线程下确保执行顺序
class ConditionClass {
Lock lock = new ReentrantLock();
HashMap<String, Object> item = null;
Condition condition = lock.newCondition();
CopyOnWriteArrayList cList = new CopyOnWriteArrayList();
def method1() {
lock.lock();
cList << "method1 开始";
item = [key: "ewing"];
Thread.sleep(500);
condition.signal();
cList << "method1 运行了5s";
cList << "method1 结束";
lock.unlock();
}
def method2() {
lock.lock();
cList << "method2 开始";
if (item == null) {
condition.await();
}
cList << "method2 唤醒";
cList << "method2 继续运行";
cList << "method2 结束";
lock.unlock();
}
}
ConditionClass conditionClass = new ConditionClass();
def cThread2 = Thread.start {
conditionClass.method2();
};
Thread.sleep(500);
def cThread1 = Thread.start {
conditionClass.method1();
};
cThread1.join();
cThread2.join();
return PluginResult.ok([item: conditionClass.item, cList: conditionClass.cList]);
7. threadlocal
class ThreadLocalDemo implements Runnable {
static ThreadLocal idCardTL = new ThreadLocal();
Map item = new HashMap();
Lock lock = new ReentrantLock();
def set(String idCard) {
idCardTL.set(idCard);
}
def firstMethod() {
lock.lock();
item.put(idCardTL.get(), "获取该身份证对应ETL校验数据");
lock.unlock();
}
@Override
void run() {
firstMethod();
}
}
ThreadLocalDemo threadLocalDemo = new ThreadLocalDemo();
ExecutorService pool = Executors.newCachedThreadPool();
IntStream.range(0, 100).each { i ->
Runnable r = {
threadLocalDemo.run();
ThreadLocalDemo.idCardTL.set(i);
}
pool.execute(r);
}
return PluginResult.ok(threadLocalDemo.item);
8. List和Map操作
retList = [:];
list = [1, 2, 3, 4, 5] as LinkedList;
map = [name: "guoyiying", nick: "ewing"];
def comparator = { x, y ->
x == y ? 0 : Math.abs(x) < Math.abs(y) ? 1 : -1;
}
def listOperator = {
retList.put(["[List]查找符合条件的所有元素", list.findAll { it > 2 }]);
retList.put(["[List]查找符合条件的第一个元素", list.find { it > 2 }]);
retList.put(["[List]符合条件的元素个数", list.count { it > 0 }]);
retList.put(["[List]是否有符合条件的元素", list.any { it > 6 }]);
retList.put(["[List]移除指定元素", list.remove((Object) 3)]);
retList.put(["[List]是否都符合条件", list.every { it > 0 }]);
retList.put(["[List]自定义排序", list.sort(comparator)]);
retList.put(["[List]获取指定范围的元素", list[1..3]]);
retList.put(["[List]遍历List", list.each {}]);
retList.put(["[List]添加元素", list << 6]);
retList.put(["[List]最大值", list.max()]);
retList.put(["[List]最小值", list.min()]);
}
def mapOperator = {
retList.put(["[Map]是否包含该键", map.containsKey("name")]);
retList.put(["[Map]修改键值", map.name = "GYY"]);
retList.put(["[Map]添加元素", map.age = 25]);
retList.put(["[Map]获取键值", map.name]);
}
listOperator.call();
mapOperator.call();
return PluginResult.ok(retList);
注: 使用到的包
import java.util.stream.IntStream;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.CountDownLatch;
import com.zqlian.common.base.PluginResult;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentSkipListMap;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.concurrent.RejectedExecutionHandler;