ThreadLocal

 ThreadLocal 每个线程的局部变量,每个访问一个线程(通过它的get或set方法)都有自己的独立初始化的变量副本。ThreadLocal实例通常是类中的私有静态字段,它们希望将状态与线程(例如,用户ID或事务ID)关联。

package com.example.learnconcurr;

//import org.apache.log4j.Logger;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.ArrayList;
import java.util.EventListener;
import java.util.concurrent.atomic.AtomicInteger;

import static java.lang.Thread.sleep;

@Slf4j
public class myTest1 {
    static final Logger logger = LoggerFactory.getLogger(myTest1.class);
    static int counter = 0;
    static Object suo = new Object();
    public static void main(String[] args) throws FileNotFoundException, InterruptedException {
        UnsafeTest unsafeTest = new UnsafeTest();
        new Thread(()->{
            System.out.println(unsafeTest.getx());
            log.debug(unsafeTest.getx().toString());
            unsafeTest.addx();
            try {
                sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(unsafeTest.getx());
            log.debug(unsafeTest.getx().toString());
        },"t1").start();

        new Thread(()->{
            System.out.println(unsafeTest.getx());
            unsafeTest.addx();
            System.out.println(unsafeTest.getx());
        },"t2").start();


    }
}
class UnsafeTest{
    ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>() {
        protected Integer initialValue(){
            return new Integer("3");
        }
    };
    //Integer threadLocal = new Integer("3");
    ArrayList<String> arrayList = new ArrayList<>();



    final public void method1(){
        for (int i = 0; i < 100; i++) {
            method2();
            method3();
        }
    }
    private void method2() {
        arrayList.add("1");
    }
    private void method3() {
        arrayList.remove(0);
    }

    public Integer getx() {
        //return threadLocal;
        return threadLocal.get();
    }
    public void addx() {
        //threadLocal++;
        threadLocal.set(threadLocal.get()+1);
    }
}

java并发学习

https://gitee.com/gu_chun_bo/java-construct/blob/master/java%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/java%E5%B9%B6%E5%8F%911.md

https://www.bilibili.com/video/BV16J411h7Rd?p=81&spm_id_from=pageDriver

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值