自旋锁

  |   0 评论   |   1,329 浏览

    
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.atomic.AtomicReference;
    
    /**
     * 自旋锁demo
     * @author tonfay
     *
     */
    public class ZiXuanLockDemo {
    	
    	AtomicReference<Thread> atomic = new AtomicReference<Thread>();
    	
    	public void lock() {
    		Thread t = Thread.currentThread();
    		while(!atomic.compareAndSet(null, t)) {
    			
    		}
    		System.out.println(Thread.currentThread().getName() + "\t 获取到锁");
    	}
    	public void unlock() {
    		Thread t = Thread.currentThread();
    		atomic.compareAndSet(t, null);
    		System.out.println(Thread.currentThread().getName() + "\t 释放锁");
    	}
    	
    	public static void main(String[] args) {
    		ZiXuanLockDemo demo = new ZiXuanLockDemo();
    		new Thread(new Runnable() {
    			@Override
    			public void run() {
    				demo.lock();
    				try {TimeUnit.SECONDS.sleep(5);} catch (InterruptedException e) {e.printStackTrace();}
    				demo.unlock();
    			}
    		},"A").start();
    		try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {e.printStackTrace();}
    		new Thread(new Runnable() {
    			@Override
    			public void run() {
    				demo.lock();
    				
    				demo.unlock();
    			}
    		},"B").start();
    	}
    }
    
    

    评论

    发表评论

    validate