在没有同步的情况下共享变量
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();
}