ThreadLocal Per-Thread State
Give each thread its own counter via ThreadLocal.withInitial so mutable per-thread state needs no locking; clear it before pooled threads get reused.
Code
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class PerThreadSteps {
// 每个线程首次 get() 时创建自己的计数器:无锁、线程间互不可见
private static final ThreadLocal<int[]> STEPS =
ThreadLocal.withInitial(() -> new int[1]);
static void step(String threadName) {
int[] counter = STEPS.get();
counter[0]++;
System.out.println(threadName + " step " + counter[0]);
}
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(2);
Runnable task = () -> {
for (int i = 0; i < 3; i++) step(Thread.currentThread().getName());
};
pool.submit(task);
pool.submit(task);
pool.shutdown();
pool.awaitTermination(5, TimeUnit.SECONDS);
System.out.println("main counter: " + STEPS.get()[0]);
STEPS.remove(); // 线程池复用线程:退出前清掉引用防泄漏
}
}How it works
Structurally, expect the class PerThreadSteps and the function step and nothing else.
Repetition is confined to for (int i = 0; i < 3; i++) step(Thread.currentThread().getName()); — the rest of the file is straight-line.
Applying it
The main signature reads static void step(String threadName)
Running the file prints labeled results such as main counter: — each operation’s effect is visible in the output.
Running the file executes main, which drives step in order.
Statements that matter
ExecutorService pool = Executors.newFixedThreadPool(2);
for (int i = 0; i < 3; i++) step(Thread.currentThread().getName());
ThreadLocal.withInitial(() -> new int[1]);
Interactive Tools for This Topic
HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.URL Safety CheckerEvaluate a URL against common phishing red flags such as plain HTTP, embedded credentials, IP hosts, Punycode, and risky top-level domains.
FAQ
- What does ThreadLocal Per-Thread State print when run?
- Execute the whole file; each printed line is prefixed with a label like `main counter:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.