Advertisement
Kostiggig

Semaphore missed signals

May 3rd, 2023
681
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.11 KB | None | 0 0
  1. package multithreading.semaphore.signaling;
  2.  
  3. public class MySemaphoreSignaling {
  4.  
  5.     private boolean wasSignal = false;
  6.  
  7.     public synchronized void acquire() throws InterruptedException {
  8.         while(!wasSignal) wait();
  9.         System.out.println(Thread.currentThread().getName() + " acquire");
  10.     }
  11.  
  12.     public synchronized void release() {
  13.         notifyAll();
  14.         wasSignal = true;
  15.         System.out.println(Thread.currentThread().getName() + " release");
  16.     }
  17. }
  18.  
  19.  
  20. Client:
  21. package multithreading.semaphore.signaling;
  22.  
  23. public class Client {
  24.  
  25.     public static void main(String[] args) throws InterruptedException {
  26.  
  27.         MySemaphoreSignaling semaphore = new MySemaphoreSignaling();
  28.         Thread threadA = new Thread(() -> {semaphore.release();});
  29.  
  30.         Thread threadB = new Thread(() -> {
  31.             try {
  32.                 semaphore.acquire();
  33.             } catch (InterruptedException e) {
  34.                 throw new RuntimeException(e);
  35.             }
  36.         });
  37.  
  38.  
  39.  
  40.         threadA.start();
  41.         threadB.start();
  42.         threadA.join();
  43.         threadB.join();
  44.     }
  45. }
  46.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement