import com.alibaba.ttl.TransmittableThreadLocal;
import com.alibaba.ttl.TtlRunnable;
import com.alibaba.ttl.threadpool.TtlExecutors;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import java.util.Date;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* TransmittableThreadLocal 测试
*/
@Slf4j
class TTLest {
@Test
void test1() throws InterruptedException {
doTest();
}
/**
* TTL 测试
*
* @throws InterruptedException
*/
public void doTest() throws InterruptedException {
TransmittableThreadLocal<String> context = new TransmittableThreadLocal<>();
// ThreadLocal<String> context = new ThreadLocal<>();
// 任务的具体方法
Runnable runnable = () -> {
System.out.println("当前任务被执行,执行时间:" + new Date() + " 执行线程:" + Thread.currentThread().getName() + "thread2 父线程数据{}" + context.get());
context.set("value-set-in-son");
System.out.println("当前任务被执行,执行时间:" + new Date() + " 执行线程:" + Thread.currentThread().getName() + "thread2 父线程数据{}" + context.get());
try {
// 等待 1s
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
};
// 创建线程,线程的任务队列的长度为 1
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(1, 1,
100, TimeUnit.SECONDS, new LinkedBlockingQueue<>(1),
new ThreadPoolExecutor.CallerRunsPolicy());
log.error("错误使用方式:1-----------------------------------");
context.set("value-set-in-parent");
// 添加并执行 4 个任务,模拟拒绝策略CallerRunsPolicy
threadPool.execute(runnable);
threadPool.execute(runnable);
threadPool.execute(runnable);
threadPool.execute(runnable);
threadPool.execute(runnable);
TimeUnit.SECONDS.sleep(5);
log.error("正确使用方式:1-----------------------------------");
context.set("value-set-in-parent");
// 添加并执行 4 个任务,模拟拒绝策略CallerRunsPolicy
threadPool.execute(TtlRunnable.get(runnable));
threadPool.execute(TtlRunnable.get(runnable));
threadPool.execute(TtlRunnable.get(runnable));
threadPool.execute(TtlRunnable.get(runnable));
threadPool.execute(TtlRunnable.get(runnable));
TimeUnit.SECONDS.sleep(5);
log.error("正确使用方式:2-----------------------------------");
context.set("value-set-in-parent");
Executor ttlThreadPool = TtlExecutors.getTtlExecutor(threadPool);
// 添加并执行 4 个任务,模拟拒绝策略CallerRunsPolicy
ttlThreadPool.execute(runnable);
ttlThreadPool.execute(runnable);
ttlThreadPool.execute(runnable);
ttlThreadPool.execute(runnable);
ttlThreadPool.execute(runnable);
// 线程池执行完任务,关闭线程池
threadPool.shutdown();
}
}
网友评论