putIfAbsent 灵活运用

2018-06-06  本文已影响0人  jackson_cai

使用场景

同一个方法只能允许同一个用户进入一次,只有运行完了之后,再允许进入。

不过是多台机器,此方式不适合,要使用分布式锁,比如使用zookeeper进行实现

测试类如下:

import org.apache.commons.lang3.RandomStringUtils;

import java.util.concurrent.ConcurrentHashMap;

import java.util.concurrent.CountDownLatch;

/**

* Created by cailu on 2018/6/6.

*/

public class Test{

    public static final ConcurrentHashMap cache = new ConcurrentHashMap();

    public static void main(String[] args) throws InterruptedException {

        CountDownLatch start = new CountDownLatch(1);

        CountDownLatch stop = new CountDownLatch(10);

        for (int i = 0; i < 10; i++) {

            RunThread runThread = new RunThread(RandomStringUtils.random(1, "ABC"), start, stop);

            Thread thread = new Thread(runThread);

            thread.start();

        }

        start.countDown();

        stop.await();

        System.out.println("全部运行完毕");

    }

    static class RunThread implements Runnable {

        private String userid;

        private CountDownLatch start;

        private CountDownLatch stop;

        public RunThread(String userid, CountDownLatch start, CountDownLatch stop) {

            this.userid = userid;

            this.start = start;

            this.stop = stop;

        }

        public void run() {

            try {

                start.await();

                RunMethod.method(userid);

            } catch (InterruptedException e) {

                e.printStackTrace();

            }finally {

                stop.countDown();

            }

        }

    }

    static class RunMethod{

        public static void method(String userid) {

            Integer key = cache.putIfAbsent(userid, 1);

            if (key != null) {

                System.out.println(userid + "|操作频繁,稍后重试");

                return;

            }

            try {

                System.out.println(userid+"|运行开始");

                try {

                    Thread.sleep(1*100);

                } catch (InterruptedException e) {

                    e.printStackTrace();

                }

                System.out.println(userid+"|运行结束");

            } catch (Exception e) {

                e.printStackTrace();

            }finally {

                cache.remove(userid);

            }

        }

    }

}

测试结果如下:

B|运行开始

C|运行开始

B|操作频繁,稍后重试

A|运行开始

B|操作频繁,稍后重试

B|操作频繁,稍后重试

C|操作频繁,稍后重试

A|操作频繁,稍后重试

C|操作频繁,稍后重试

B|操作频繁,稍后重试

C|运行结束

B|运行结束

A|运行结束

全部运行完毕

上一篇 下一篇

猜你喜欢

热点阅读