AtomicInteger原子雷类型自增

AtomicInteger原子操作类型:

private static Integer num = 0; 对num++得到结果19055

private static volatile Integer num = 0; 对num++得到结果19550

此时引入java并发包下的AtomicInteger类,利用其原子操作实现高并发问题解决:

public class MyAtomicInteger { private static final Integer threadCount = 20;

private static AtomicInteger count = new AtomicInteger(0); private static void increase() { count.incrementAndGet(); }

public static void main(String[] args) { Thread[] threads = new Thread[threadCount]; for (int i = 0; i < threadCount; i++) { threads[i] = new Thread(() -> { for (int i1 = 0; i1 < 1000; i1++) { increase(); } }); threads[i].start(); }

while (Thread.activeCount() > 1) {

// 意思就是调用yield方法会让当前线程交出CPU权限,让CPU去执行其他的线程。它跟sleep方法类似,同样不会释放锁。// 但是yield不能控制具体的交出CPU的时间,另外,yield方法只能让拥有相同优先级的线程有获取CPU执行时间的机会。// 注意调用yield方法并不会让线程进入阻塞状态,而是让线程重回就绪状态,它只需要等待重新获取CPU执行时间,这一点是和sleep方法不一样的 Thread.yield(); } System.out.println(Thread.currentThread().getName()); System.out.println("num:" + count); }}

结果:

main

num:40000

猜你喜欢

转载自www.cnblogs.com/tian-Bao555/p/12128433.html