ThreadLocal用法
1.ThreadLocal
通过get获取线程中的Map
import java.util.concurrent.atomic.AtomicInteger;
public class ThreadId {
// Atomic integer containing the next thread ID to be assigned
private static final AtomicInteger nextId = new AtomicInteger(0);
// Thread local variable containing each thread's ID
private static final ThreadLocal<Integer> threadId =
new ThreadLocal<Integer>() {
@Override protected Integer initialValue() {
return nextId.getAndIncrement();
}
};
// Returns the current thread's unique ID, assigning it if necessary
public static int get() {
return threadId.get();
}
}
接着,我们可以使用两个线程去分别读取ThreadLocal中的值,我们会发现并不会发生两个值有并行的问题,这也是ThreadLocal的设计思想,为了解决线程同步的问题,我们将ThreadLocal中的值复制到每一个线程中。
子线程和父线程的数据传递
InheritableThreadLocal允许子线程和父线程进行数据传递。
ThreadLocal的图示如下:
总结:ThreadLocal主要为了在多线程中,防止同步的问题而设置的。每个线程均存在单独的线程内存。
Volatile
在多线程的操作中,为了保证所有的线程中访问的数据一致,使用Volatile关键字,使得每次的读取都在主内存而不是在缓存中读取,防止脏读。
保证主内存中一直保存着最新数据,而不是cache为主的保存
Example:
public class MyClass {
private int years;
private int months
private volatile int days;
public void update(int years, int months, int days){
this.years = years;
this.months = months;
this.days = days;
}
}
如果包含一个volatile属性,那么对三个属性同时更新的时候,三个属性都会一起写入主内存。
一个光使用Volatile关键字也不够的例子,解决的办法包括使用同步代码块,保证一个时间只有一个线程能对数据进行操作
Condition
未完待续。。。
Reentrant Lock
未完待续。。。