當前位置:編程學習大全網 - 源碼下載 - putIfAbsent 靈活運用

putIfAbsent 靈活運用

使用場景

同壹個方法只能允許同壹個用戶進入壹次,只有運行完了之後,再允許進入。

不過是多臺機器,此方式不適合,要使用分布式鎖,比如使用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|運行結束

全部運行完畢

  • 上一篇:用java怎麽實現QQ登錄界面?
  • 下一篇:同心協力的成語接龍?
  • copyright 2024編程學習大全網