自己實現一個CAS小程序

package com.hrfax;

import sun.misc.Unsafe;

import java.lang.reflect.Field;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

public class MyCas {
    static MyLock lock = new MyLock();
    public static void main(String[] args) throws InstantiationException {
        Task task = new Task();
        Thread t1 = new Thread(task);
        Thread t2 = new Thread(task);
        Thread t3 = new Thread(task);
        t1.start();
        t2.start();
        t3.start();
    }

    static class MyLock{

        LinkedBlockingQueue<Thread> threads = new LinkedBlockingQueue<>();
        static final long stateOffset;
        static final Unsafe theUnsafe;
        volatile long state = 0;
        static {
            try {
                Field field = Unsafe.class.getDeclaredField("theUnsafe");
                field.setAccessible(true);
                theUnsafe = (Unsafe) field.get(null);
                stateOffset = theUnsafe.objectFieldOffset(MyLock.class.getDeclaredField("state"));
            }catch (Exception e){
                e.printStackTrace();
                throw new Error(e);
            }
        }
        public void lock(){
            while(!theUnsafe.compareAndSwapInt(state,stateOffset,0,1)){
                threads.offer(Thread.currentThread());
                LockSupport.park();
            }
        }
        public void unLock(){
            while(theUnsafe.compareAndSwapInt(state,stateOffset,1,0)){
                Thread poll = threads.poll();
                LockSupport.unpark(poll);
            }
        }
    }

    static class Task implements Runnable{

        @Override
        public void run() {
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + "啓動了。。。。。");
                TimeUnit.SECONDS.sleep(3);
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                lock.unLock();
            }
        }

    }

}
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章