Advertisement
Guest User

Untitled

a guest
Mar 27th, 2017
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.73 KB | None | 0 0
  1. package cz.jlochman.lochness.core.aa;
  2.  
  3. import java.util.Random;
  4. import java.util.concurrent.ConcurrentHashMap;
  5. import java.util.concurrent.ConcurrentMap;
  6. import java.util.concurrent.ExecutorService;
  7. import java.util.concurrent.Executors;
  8. import java.util.concurrent.TimeUnit;
  9. import java.util.concurrent.locks.ReentrantLock;
  10.  
  11. public class MutexTest {
  12.  
  13.     public static void main(String[] args) {
  14.         MutexTest test = new MutexTest();
  15.         test.work();
  16.     }
  17.  
  18.     private ConcurrentMap<Integer, ReentrantLock> locks = new ConcurrentHashMap<>();
  19.     private ExecutorService executor = Executors.newFixedThreadPool(4);
  20.  
  21.     public void work() {
  22.         Random rand = new Random();
  23.         for (int i = 0; i < 12; i++) {
  24.             int hash = rand.nextInt(4);
  25.             submitTask(hash);
  26.         }
  27.         stop();
  28.     }
  29.  
  30.     private void submitTask(int hash) {
  31.         locks.putIfAbsent(hash, new ReentrantLock());
  32.  
  33.         executor.submit(() -> {
  34.             ReentrantLock lock = locks.get(hash);
  35.             if (lock.isLocked()) {
  36.                 System.out.println(Thread.currentThread().getName() + "... is waiting: " + hash);
  37.             }
  38.             lock.lock();
  39.             try {
  40.                 System.out.println(Thread.currentThread().getName() + "... is woorking: " + hash);
  41.                 sleep(5);
  42.             } finally {
  43.                 lock.unlock();
  44.             }
  45.         });
  46.  
  47.     }
  48.  
  49.     private void stop() {
  50.         try {
  51.             executor.shutdown();
  52.             executor.awaitTermination(60, TimeUnit.SECONDS);
  53.         } catch (InterruptedException e) {
  54.             System.err.println("termination interrupted");
  55.         } finally {
  56.             if (!executor.isTerminated()) {
  57.                 System.err.println("killing non-finished tasks");
  58.             }
  59.             executor.shutdownNow();
  60.         }
  61.     }
  62.  
  63.     private void sleep(int seconds) {
  64.         try {
  65.             TimeUnit.SECONDS.sleep(seconds);
  66.         } catch (InterruptedException e) {
  67.             throw new IllegalStateException(e);
  68.         }
  69.     }
  70.  
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement