Atomic 变量具有原子化
下面代码片段中,isSet 原子化操作,可以防止在多线程环境中线程被起动多次
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
public class AutomicTest {
static AtomicBoolean isSet = new AtomicBoolean(false);
static AtomicInteger threadslot = new AtomicInteger(0);
public static void main(String args[]){
if(isSet.compareAndSet(false, true))
{
new Thread(String.valueOf(threadslot.incrementAndGet())){
public void run()
{
System.out.println("thread name is:"+ this.getName());
}
};
}
}
}