对象的共享

在没有同步的情况下共享变量

public class  ReaderThread  extends  Thread{
    private static  boolean ready;
    private  static  int number;
    public  void  run(){
        while (!ready){
            Thread.yield();
            System.out.println(number);
        }
    }

    public static void main(String[] args) {
        ReaderThread readerThread = new ReaderThread();
        number=42;
        ready = true;
    }

非线程安全的变整数类

@NotThreadSafe
public class MutableInteger {

    private  int value;

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }
}

线程安全的可变整数类

@ThreadSafe
public class SynchronizedInteger {

    @GuardedBy("this") private  int value;

    public synchronized int getValue() {
        return value;
    }

    public synchronized  void setValue(int value) {
        this.value = value;
    }
}

基本类型的局部变量与引用变量的线程封闭性

public int loadTheArk(Collection<Object> collections) {
    SortedSet<Object> objects;
    int munPairs = 0;
    Object o = null;
    //objects   被封闭在方法中,不要使用它们逸出
    objects = new TreeSet<Object>(new ArrayList<>());
    objects.addAll(collections);
    for (Object object : objects) {
        if (o == null) {
            o = object;
        } else {
            ++munPairs;
            o = null;
        }
    }
    return munPairs;
}

使用ThreadLocal来维持线程封闭性

private  static  ThreadLocal<Collection> colrelectionThreadLocal = new ThreadLocal<Collection>(){

    @SneakyThrows
    public  Collection initialValue(){
        return (Collection) DriverManager.getConnection("111");
    }
};

public  static  Collection getConnection(){
    return  colrelectionThreadLocal.get();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值