美文网首页
多线程6原子类

多线程6原子类

作者: RyanHugo | 来源:发表于2020-03-22 10:42 被阅读0次

    代码

    import java.util.concurrent.atomic.AtomicInteger;
    import java.util.concurrent.atomic.AtomicIntegerArray;
    import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
    import java.util.concurrent.atomic.AtomicReference;
    import java.util.function.IntUnaryOperator;
    
    public class Sequence {
    
        private AtomicInteger value = new AtomicInteger();
        private int s[]={2,1,4,5,6};
        AtomicIntegerArray a = new AtomicIntegerArray(s);
        AtomicReference<User> user = new AtomicReference<User>();
        AtomicIntegerFieldUpdater<User> old = AtomicIntegerFieldUpdater.newUpdater(User.class, "old");
        /*
         *  public final int getAndUpdate(IntUnaryOperator updateFunction) {
            int prev, next;
            do {
                prev = get();
                next = updateFunction.applyAsInt(prev);
            } while (!compareAndSet(prev, next));
            return prev;
        }底层采用cas操作,获取当前值和预期的下个值,cas比较,为真则返回
         * 
         */
        public int getNext(){
            return value.getAndIncrement();             
        }
        
        public void getArrayNexy(){
            
            old.getAndIncrement(new User());
    //      数组第二个位置的元素加10
            a.addAndGet(1, 10);
            a.getAndIncrement(1);
        }
        
        public static void main(String[] args) {
            Sequence s = new Sequence();
            
            
            new Thread(new Runnable() {
                
                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    while (true) {
                        System.out.println(Thread.currentThread().getName() + " "+s.getNext());
                        try {
                            Thread.sleep(100);
                        } catch (Exception e) {
                            // TODO: handle exception
                        }
                    }
                }
            }).start();
            
            new Thread(new Runnable() { 
                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    while (true) {
                        System.out.println(Thread.currentThread().getName() + " "+s.getNext());
                        try {
                            Thread.sleep(100);
                        } catch (Exception e) {
                            // TODO: handle exception
                        }
                    }
                }
            }).start();
            
        }
    }
    

    相关文章

      网友评论

          本文标题:多线程6原子类

          本文链接:https://www.haomeiwen.com/subject/dbemyhtx.html