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("static-access") public static void main(String[] args) { for (int i = 0; i < 100000; i++) { Thread thread = new Thread(new SpinLockTest()); thread.start(); } System.out.println("here"); try { Thread.currentThread().sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(count); } @Override public void run() { spinLock.lock(); count++; spinLock.unlock(); } } /** * 自旋锁 让其他线程不断的循环等待着去用自身线程引用去加锁(当锁的竞争不大且,锁的时间段比较长的时候适用)。 */ class SpinLock { private AtomicReference<Thread> sign = new AtomicReference<Thread>(); public void lock() { Thread 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); } }
时间: 2024-10-06 09:49:08