一百、ThreadLocal之是什么能干嘛
ThreadLocal<T> 该类提供线程局部变量
1、ThreadLocal简介
①、大厂面试题
②、是什么?
③、能干嘛?
④、方法摘要
一百零一、ThreadLocal之案例编码实战
package com.nanjing.juc.tl;
import java.util.Random;
import java.util.concurrent.TimeUnit;
/**
* 需求一: 5个销售卖房子,集团高层只关心销售总量的准确统计数。
*
* 需求二: 5个销售卖完随机数房子,各自独立销售额度,自己业绩按提成走,分灶吃饭,各个销售自己动手,丰衣足食
*
* @author xizheng
* @date 2023-08-21 18:28:26
*/
class House{//资源类
int saleCout = 0;
public synchronized void saleHouse(){
++saleCout;
}
//匿名内部类,繁琐麻烦,推荐使用下面的初始值
// ThreadLocal<Integer> saleVolume = new ThreadLocal<Integer>(){
// @Override
// protected Integer initialValue() {
// return 0;
// }
// };
ThreadLocal<Integer> saleVolume = ThreadLocal.withInitial(() -> 0);
public void saleVolumeByThreadLocal(){
saleVolume.set(1+saleVolume.get());
}
}
public class ThreadLocalDemo {
public static void main(String[] args) {
House house = new House();
for (int i = 1; i <= 5; i++) {
new Thread(() -> {
int size = new Random().nextInt(5)+1;
//System.out.println(size);
try {
for (int j = 0; j < size; j++) {
house.saleHouse();
house.saleVolumeByThreadLocal();
}
System.out.println(Thread.currentThread().getName()+"\t"+"号销售卖出: "+house.saleVolume.get());
} finally {
house.saleVolume.remove();
}
},String.valueOf(i)).start();
}
//暂停毫秒
try {
TimeUnit.MILLISECONDS.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"\t"+"共计,卖出多少套: "+house.saleCout);
}
}