Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package cz.jlochman.lochness.core.aa;
- import java.util.Random;
- import java.util.concurrent.ConcurrentHashMap;
- import java.util.concurrent.ConcurrentMap;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.concurrent.TimeUnit;
- import java.util.concurrent.locks.ReentrantLock;
- public class MutexTest {
- public static void main(String[] args) {
- MutexTest test = new MutexTest();
- test.work();
- }
- private ConcurrentMap<Integer, ReentrantLock> locks = new ConcurrentHashMap<>();
- private ExecutorService executor = Executors.newFixedThreadPool(4);
- public void work() {
- Random rand = new Random();
- for (int i = 0; i < 12; i++) {
- int hash = rand.nextInt(4);
- submitTask(hash);
- }
- stop();
- }
- private void submitTask(int hash) {
- locks.putIfAbsent(hash, new ReentrantLock());
- executor.submit(() -> {
- ReentrantLock lock = locks.get(hash);
- if (lock.isLocked()) {
- System.out.println(Thread.currentThread().getName() + "... is waiting: " + hash);
- }
- lock.lock();
- try {
- System.out.println(Thread.currentThread().getName() + "... is woorking: " + hash);
- sleep(5);
- } finally {
- lock.unlock();
- }
- });
- }
- private void stop() {
- try {
- executor.shutdown();
- executor.awaitTermination(60, TimeUnit.SECONDS);
- } catch (InterruptedException e) {
- System.err.println("termination interrupted");
- } finally {
- if (!executor.isTerminated()) {
- System.err.println("killing non-finished tasks");
- }
- executor.shutdownNow();
- }
- }
- private void sleep(int seconds) {
- try {
- TimeUnit.SECONDS.sleep(seconds);
- } catch (InterruptedException e) {
- throw new IllegalStateException(e);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement