Advertisement
Kostiggig

Untitled

May 3rd, 2023
780
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.86 KB | None | 0 0
  1.  
  2. package multithreading.semaphore.syncrhonization;
  3.  
  4. import java.util.ArrayList;
  5. import java.util.List;
  6.  
  7. public class SharedResource {
  8.  
  9.     private final MySynchronizedSemaphore semaphore;
  10.     public final List<String> data = new ArrayList<>();
  11.  
  12.     public SharedResource(MySynchronizedSemaphore semaphore) {
  13.         this.semaphore = semaphore;
  14.     }
  15.  
  16.     public void doSomeAtomicStuff() throws InterruptedException {
  17.         semaphore.acquire();
  18.         data.add(Thread.currentThread().getName());
  19.         semaphore.release();
  20.     }
  21.  
  22. }
  23.  
  24.  
  25. package multithreading.semaphore.syncrhonization;
  26.  
  27. import java.util.ArrayList;
  28. import java.util.List;
  29.  
  30. public class SharedResource {
  31.  
  32.     private final MySynchronizedSemaphore semaphore;
  33.     public final List<String> data = new ArrayList<>();
  34.  
  35.     public SharedResource(MySynchronizedSemaphore semaphore) {
  36.         this.semaphore = semaphore;
  37.     }
  38.  
  39.     public void doSomeAtomicStuff() throws InterruptedException {
  40.         semaphore.acquire();
  41.         data.add(Thread.currentThread().getName());
  42.         semaphore.release();
  43.     }
  44.  
  45. }
  46.  
  47.  
  48. Client
  49. package multithreading.semaphore.syncrhonization;
  50.  
  51. public class Client {
  52.  
  53.     public static void main(String[] args) throws InterruptedException {
  54.         MySynchronizedSemaphore semaphore = new MySynchronizedSemaphore();
  55.         SharedResource sharedResource = new SharedResource(semaphore);
  56.         for (int i = 0; i < 500_000; i++) {
  57.             Thread thread = new Thread(() -> {
  58.                 try {
  59.                     sharedResource.doSomeAtomicStuff();
  60.                 } catch (InterruptedException e) {
  61.                     throw new RuntimeException(e);
  62.                 }
  63.             });
  64.             thread.start();
  65.             thread.join();
  66.         }
  67.  
  68.         System.out.println("Size of the list is " + sharedResource.data.size());
  69.     }
  70. }
  71.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement