In order to prevent unscrupulous site crawler crawling articles, hereby identified, reproduced please indicate the source of the article. Laplacedemon/shijiaqi.
http://www.cnblogs.com/shijiaqi1066/p/5999610.html
Realize:
PackageSjq.mylock;Importjava.util.concurrent.atomic.AtomicReference; Public classSpinLock {PrivateAtomicreference<thread> owner =NewAtomicreference<>(); Public voidLock () {Thread CurrentThread=Thread.CurrentThread (); while(!owner.compareandset (NULL, CurrentThread)) {//owner = = NULL, then Compareandset returns True, otherwise false. //can't get the owner's thread, constantly in the dead loop } } Public voidUnLock () {Owner.set (NULL); //It can also be written, too troublesome, not necessary /*Thread cur = thread.currentthread (); Owner.compareandset (cur, null); */ } }
Test:
PackageSjq.mylock;ImportJava.util.concurrent.CountDownLatch;Importorg.junit.Test; Public classTestspinlock {Final Static intThread_num = 100; Static intx = 0; @Test Public voidTestlock ()throwsinterruptedexception {countdownlatch latch=NewCountdownlatch (Thread_num); //LockSpinLock SpinLock =NewSpinLock (); for(inti = 0; i < Thread_num; i++) { //start a child thread NewThread (() { //each thread loops multiple times, locks frequently, unlocks. for(intn = 0; n < 100; n++) {spinlock.lock (); X++; Spinlock.unlock (); } latch.countdown (); //the child thread notifies the main thread that the work is complete. }). Start (); } latch.await (); //The main thread waits for all child threads to end. System.out.println (x); //Final Print Result: 10000, no thread unsafe exception occurred. }}
In order to prevent unscrupulous site crawler crawling articles, hereby identified, reproduced please indicate the source of the article. Laplacedemon/shijiaqi.
http://www.cnblogs.com/shijiaqi1066/p/5999610.html
Implementing a spin lock with the CAs method of the Java Atom variable