这8种保证线程安全的技术你都知道吗?
无状态 不可变 安全的发布 volatile synchronized lock cas threadlocal
一.无状态
public class NoStatusService {
public void add(String status) {
System.out.println("add status:" + status);
}
public void update(String status) {
System.out.println("update status:" + status);
}
}
二.不可变
public class NoChangeService {
public static final String DEFAULT_NAME = "abc";
public void add(String status) {
System.out.println("add status:" + status);
}
}
三.安全的发布
public class SafePublishService {
private String name;
public String getName() {
return name;
}
public void add(String status) {
System.out.println("add status:" + status);
}
}
四.volatile
public class FlagService {
public volatile boolean flag = false;
public void change() {
if (flag) {
System.out.println("return");
return;
}
flag = true;
System.out.println("change");
}
}
五.synchronized
public class SyncService {
private int age = 1;
public synchronized void add(int i) {
age = age + i;
System.out.println("age:" + age);
}
public void update(int i) {
synchronized (this) {
age = age + i;
System.out.println("age:" + age);
}
}
}
六.lock
public class LockService {
private ReentrantLock reentrantLock = new ReentrantLock();
public int age = 1;
public void add(int i) {
try {
reentrantLock.lock();
age = age + i;
System.out.println("age:" + age);
} finally {
reentrantLock.unlock();
}
}
}
七.cas
public class AtomicService {
private AtomicInteger atomicInteger = new AtomicInteger();
public int add(int i) {
return atomicInteger.getAndAdd(i);
}
}
八.threadlocal
public class ThreadLocalService {
private ThreadLocal
threadLocal = new ThreadLocal<>();
public void add(int i) {
Integer integer = threadLocal.get();
threadLocal.set(integer == null ? 0 : integer + i);
}
}
总结
有道无术,术可成;有术无道,止于术
欢迎大家关注Java之道公众号
好文章,我在看❤️
评论