Package Spinlock;import Java.util.concurrent.atomic.atomicreference;public class Spinlocktest implements Runnable{ private static int count = 0;private static SpinLock SpinLock = new SpinLock ();/** * @param args */@SuppressWarnings ("Stat Ic-access ") public static void main (string[] args) {for (int i = 0; i < 100000; i++) {Thread thread = new Thread (new SPI Nlocktest ()); Thread.Start ();} System.out.println ("Here"), try {thread.currentthread (). Sleep (), and catch (Interruptedexception e) { E.printstacktrace ();} System.out.println (count);} @Overridepublic void Run () {spinlock.lock (); Count++;spinlock.unlock ();}} /** * Spin lock allows other threads to constantly loop around waiting to use their own thread references to locking (when the lock is not very competitive and the time period for the lock is longer). */class SpinLock {private atomicreference<thread> sign = new atomicreference<thread> (), public void Lock () {T Hread current = Thread.CurrentThread (); System.out.println (Thread.CurrentThread (). GetName () + "Wait"), while (!sign.compareandset (null, current)) {}}public void Unlock () {Thread current = Thread.CurrentThread (); SiGn.compareandset (current, null);}}
Java Spin Lock