package Juc;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;
/**
* 测试锁的可见性
*
*/
public class ThreadSafeCache {
volatile int Result=0;
public int getResult() {
return Result;
}
AtomicInteger atomicInteger=new AtomicInteger();
ReentrantLock lock = new ReentrantLock();
public void setResult() {
/*lock.lock();
try {
Result++;
} finally {
lock.unlock();
}*/
atomicInteger.getAndIncrement();
}
public static void main(String[] args) {
ThreadSafeCache syc= new ThreadSafeCache();
for (int i = 0; i < 1000; i++) {
new Thread(() -> {
for (int j = 0; j < 10000; j++) {
syc.setResult();
}
},String.valueOf(i)).start();
}
while(Thread.activeCount()>2){ //默认2个线程,main线程和Gc线程。
Thread.yield(); //礼让线程
}
System.out.println(syc.Result+"======"+syc.atomicInteger);
}
}
AtomicInteger原子整形与ReentrantLock锁
最新推荐文章于 2021-05-17 16:39:53 发布