用了ThreadLocal还是有重复值
相关代码:
package thread_learn;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadStringBuilder {
public static ExecutorService executorService = Executors.newFixedThreadPool(10);
public static void main(String[] args) {
for (int i = 0; i < 20; i++) {
int fianl = i;
executorService.submit(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(ThreadSafeStringBuilder.getString(fianl));
}
});
}
}
}
相关代码:
package thread_learn;
public class ThreadSafeStringBuilder {
public static ThreadLocal<StringBuilder> stringBuilderThreadLocal = ThreadLocal.withInitial(() -> new StringBuilder());
public static String getString(int number) {
StringBuilder stringBuilder = ThreadSafeStringBuilder.stringBuilderThreadLocal.get();
stringBuilder.append("数字" + number+" ");
stringBuilder.append(Thread.currentThread().getName());
return stringBuilder.toString();
}
}
31
收起
正在回答 回答被采纳积分+1
1回答
java工程师2020版
- 参与学习 人
- 提交作业 9393 份
- 解答问题 16556 个
综合就业常年第一,编程排行常年霸榜,无需脱产即可学习,北上广深月薪过万 无论你是未就业的学生还是想转行的在职人员,不需要基础,只要你有梦想,想高薪
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星