|
| 1 | +package top.cadecode.uniboot.demo.controller; |
| 2 | + |
| 3 | +import com.alibaba.ttl.TransmittableThreadLocal; |
| 4 | +import com.alibaba.ttl.threadpool.TtlExecutors; |
| 5 | +import io.swagger.annotations.Api; |
| 6 | +import io.swagger.annotations.ApiOperation; |
| 7 | +import lombok.RequiredArgsConstructor; |
| 8 | +import lombok.extern.slf4j.Slf4j; |
| 9 | +import org.springframework.web.bind.annotation.PostMapping; |
| 10 | +import org.springframework.web.bind.annotation.RequestMapping; |
| 11 | +import org.springframework.web.bind.annotation.RestController; |
| 12 | +import top.cadecode.uniboot.common.annotation.ApiFormat; |
| 13 | + |
| 14 | +import java.util.concurrent.Executor; |
| 15 | +import java.util.concurrent.Executors; |
| 16 | + |
| 17 | +/** |
| 18 | + * 阿里 TransmittableThreadLocal 测试 |
| 19 | + * |
| 20 | + * @author Cade Li |
| 21 | + * @date 2023/3/13 |
| 22 | + */ |
| 23 | +@ApiFormat |
| 24 | +@Slf4j |
| 25 | +@RequiredArgsConstructor |
| 26 | +@Api(tags = "TransmittableThreadLocal 测试") |
| 27 | +@RestController |
| 28 | +@RequestMapping("demo/ttl") |
| 29 | +public class TtlExecutorController { |
| 30 | + |
| 31 | + @ApiOperation("测试普通 ThreadLocal") |
| 32 | + @PostMapping("test_thread_local") |
| 33 | + public String testThreadLocal() { |
| 34 | + ThreadLocal<String> threadLocal = new ThreadLocal<>(); |
| 35 | + threadLocal.set("A"); |
| 36 | + Executor executor = Executors.newFixedThreadPool(2); |
| 37 | + for (int i = 0; i < 5; i++) { |
| 38 | + executor.execute(() -> { |
| 39 | + // 前两个线程打印出 null,因为普通的 ThreadLocal 不能被子线程继承 |
| 40 | + System.out.println(threadLocal.get()); |
| 41 | + threadLocal.set("B"); |
| 42 | + // 修改了之后,后续线程被复用时会打印出修改后的值 |
| 43 | + }); |
| 44 | + } |
| 45 | + return "OK"; |
| 46 | + } |
| 47 | + |
| 48 | + @ApiOperation("测试 TransmittableThreadLocal") |
| 49 | + @PostMapping("test_ttl") |
| 50 | + public String testTransmittableThreadLocal() { |
| 51 | + ThreadLocal<String> threadLocal = new TransmittableThreadLocal<>(); |
| 52 | + threadLocal.set("A"); |
| 53 | + Executor executor = TtlExecutors.getTtlExecutor(Executors.newFixedThreadPool(2)); |
| 54 | + for (int i = 0; i < 5; i++) { |
| 55 | + executor.execute(() -> { |
| 56 | + System.out.println(threadLocal.get()); |
| 57 | + threadLocal.set("B"); |
| 58 | + // 使用 ttl 后,5 次都打印出 A,说明 ttl 可以被子线程继承,并且线程复用时没有相互影响 |
| 59 | + }); |
| 60 | + } |
| 61 | + return "OK"; |
| 62 | + } |
| 63 | +} |
0 commit comments