Advertisement
josiftepe

Untitled

Mar 31st, 2021
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.98 KB | None | 0 0
  1. import javax.swing.text.StyleContext;
  2. import java.sql.SQLOutput;
  3. import java.util.concurrent.Semaphore;
  4. import java.util.concurrent.locks.Lock;
  5. import java.util.concurrent.locks.ReentrantLock;
  6.  
  7. public class Main {
  8.     public static void main(String[] args) throws  InterruptedException{
  9.         Incrementor i = new Incrementor();
  10.         Incrementor i2 = new Incrementor();
  11.         MyThread t1 = new MyThread(1, i);
  12.         MyThread t2 = new MyThread(2, i2);
  13.        t1.start();
  14.        t2.start();
  15.        t1.join();
  16.        t2.join();
  17.         System.out.println(i.getCount());
  18.         System.out.println(i2.getCount());
  19.     }
  20. }
  21. class MyThread extends Thread {
  22.     int id;
  23.     Incrementor incrementor;
  24.     public MyThread(int _id, Incrementor i) {
  25.         id = _id;
  26.         incrementor = i;
  27.     }
  28.     @Override
  29.     public void run() {
  30.  
  31.         for(int i = 0; i < 20; i++) {
  32. //            System.out.println("Thread " + id + " " + i);
  33.             incrementor.safe_semaphore_increment();
  34.         }
  35.  
  36.     }
  37. }
  38. class Incrementor {
  39.     private static int count = 0;
  40.     private static Lock lock = new ReentrantLock();
  41.     private static Semaphore semaphore = new Semaphore(2);
  42.     public static void not_safe_increment() {
  43.         ++count;
  44.         try {
  45.             Thread.sleep(5);
  46.         }
  47.         catch (InterruptedException ei) {
  48.             System.out.println(ei);
  49.         }
  50.         }
  51.         public  void safe_increment() {
  52.             synchronized (this) {
  53.                 count++;
  54.             }
  55.         }
  56.         public static void safe_mutex_increment() {
  57.         lock.lock();
  58.         count++;
  59.         lock.unlock();
  60.         }
  61.         public static void safe_semaphore_increment() {
  62.         try {
  63.             semaphore.acquire();
  64.             count++;
  65.             semaphore.release();
  66.         }
  67.         catch (InterruptedException ie) {
  68.             System.out.println(ie);
  69.         }
  70.  
  71.         }
  72.     public static int getCount() {
  73.         return count;
  74.     }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement