zoukankan      html  css  js  c++  java
  • 手动实现自旋锁

    package com.test;
    
    import java.util.concurrent.atomic.AtomicReference;
    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;
    /**
     * 手动写一个自旋锁
     * @author renyahui
     *
     */
    public class SelfCircleLock {
        //原子引用线程
        AtomicReference<Thread> atomicReference=new AtomicReference<Thread>(); 
        
        public void myLock(){
            Thread thread=Thread.currentThread();
            System.out.println(thread.getName()+"	 come in……");
            while(!atomicReference.compareAndSet(null, thread)){
                //System.out.println("加锁自我旋转中……");
            }
            
        }
        
        public void myUnLock(){
            Thread thread=Thread.currentThread();
            System.out.println(thread.getName()+"	  invoke myunlock……");
            while(!atomicReference.compareAndSet(thread, null)){
                System.out.println("解锁自我旋转中……");
            }
            
            
        }
    
    public static void main(String[] args) {
        final SelfCircleLock selfCircle=new SelfCircleLock();
        
        new Thread(
             new Runnable() {
                
                public void run() {
                    selfCircle.myLock();
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    selfCircle.myUnLock();
                }
            
        }).start();
        
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        
        new Thread(
                 new Runnable() {
                    
                    public void run() {
                        selfCircle.myLock();
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        selfCircle.myUnLock();
                    }
                
            }).start();
    
    }
    }
  • 相关阅读:
    【LA3461】Leonardo的笔记本
    【洛谷P3708】Koishi的数学题
    【Uva11762】Race to 1
    【uva11421】玩纸牌
    【反演复习计划】【51nod1594】Gcd and Phi
    【乱入】Uva11021麻球繁衍
    【反演复习计划】【bzoj4407】于神之怒加强版
    BZOJ3293: [Cqoi2011]分金币
    BZOJ2400: Spoj 839 Optimal Marks
    BZOJ1391: [Ceoi2008]order
  • 原文地址:https://www.cnblogs.com/jiawen010/p/12375530.html
Copyright © 2011-2022 走看看