Java Spin Lock

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.