使用 AtomicInteger 的线程如何减少上下文切换次数?

How does a thread using AtomicInteger does less number of context switching?

我正在研究 AutomaticInteger。它指出使用 AtomicInteger 可以使整数操作成为非阻塞的。据说 AtomicInteger 的 compareAndSet() 方法利用了 Compare-and-set 特性。如果不成功,比较并设置功能 returns false。为了使 Compare-and-set 成功,AtomicInteger 的 compareAndSet() 方法必须在无限循环中使用它。据说由于整数运算很小,所以在循环中等待比切换上下文更有好处。

据我了解,每个线程都有固定的可用时间量。如果一个线程不能在它的时间片内完成它的工作,它就必须被抢占。那以后再有机会吧。

所以我的问题是:

  1. 在无法获得 Synchronized 方法或块上的锁后,是否有任何线程在其时间片到期之前被抢占?如果是,该线程何时再次获得 CPU 时间?
  2. AtomicInteger 的 compareAndSet() 方法中存在的一种自旋锁(无限循环)如何 class 能够减少上下文切换时间?

After being unable to gain a lock on the Synchronized method or block, is any thread preempted before its time quanta expire? If yes, when does that thread get CPU time again?

这取决于调度程序。但是如果线程得到pre-empted,那只是因为有其他线程可以立即向前推进

How is a kind of spinlock (infinite loop) present in compareAndSet() method of AtomicInteger class able to reduce the context switch time?

它只会在 AtomicInteger 被修改时循环,在这种情况下,这意味着另一个线程取得了进展。无论如何,两个线程不能通过同时修改同一个共享资源来取得进展。如果它循环很多,这意味着其他线程正在取得很多进展。在现实条件下,一个线程旋转两次以上的情况非常罕见,而且这仍然比不必要的上下文切换更便宜。