多執行緒測驗代碼:
package net.dreamzuora.utils;
import java.util.UUID;
import java.util.concurrent.*;
public class ThreadLocalMultiThread {
ThreadLocal<String> threadLocal = new ThreadLocal<>();
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(1);
ThreadPoolExecutor.CallerRunsPolicy callerRunsPolicy = new ThreadPoolExecutor.CallerRunsPolicy();
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 10, 3, TimeUnit.SECONDS, new ArrayBlockingQueue<>(200), new MyThreadFactory(), callerRunsPolicy);
ThreadLocalMultiThread threadLocalMultiThread = new ThreadLocalMultiThread();
for (int k =0; k < 500; k++){
threadPoolExecutor.execute(threadLocalMultiThread.new TestWorker());
}
countDownLatch.await();
}
class TestWorker implements Runnable{
@Override
public void run() {
try {
String s = UUID.randomUUID().toString();
System.out.println(System.currentTimeMillis() + " " + Thread.currentThread().getName() + " producer : " + s);
threadLocal.set(s);
TimeUnit.SECONDS.sleep(1);
System.out.println(System.currentTimeMillis() + " " + Thread.currentThread().getName() + "consumer : " + threadLocal.get());
threadLocal.remove();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
static int i = 0;
static class MyThreadFactory implements ThreadFactory{
@Override
public Thread newThread(Runnable r) {
return new Thread(r, "my thread-" + i++);
}
}
}
輸出結果:

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/257754.html
標籤:其他
上一篇:攻防世界新手區
