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();
}
}
TransmittableThreadLocal 测试
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- Markdown 是一种轻量级标记语言,它允许人们使用易读易写的纯文本格式编写文档,然后转换成格式丰富的HTML页...
- 小白板:评论的附件功能;评论通知跳转评论页面; IM:公司/团队/已解散群组的标识;附件上传及预览;置顶;消息免打...
- 项目前期、中期至发布后测试启动前后我们一般要经历的几种测试方法。 1 > 单元测试 是指对软件中最小可测试单元进行...