Advertisement
Martina312

Untitled

Apr 7th, 2020
512
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.26 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.List;
  3. import java.util.concurrent.Semaphore;
  4.  
  5. public class Singleton extends Thread{
  6.  
  7.     private static volatile Singleton singleton;
  8.     static Semaphore access=new Semaphore(1);
  9.     static int count=0;
  10.     static int created=0;
  11.     private Singleton() {}
  12.  
  13.     public static Singleton getInstance() throws InterruptedException {
  14.         // TODO: 3/29/20 Synchronize this
  15.         access.acquire();
  16.         count++;
  17.         if(count==1){
  18.             singleton = new Singleton();
  19.             created++;
  20.         }
  21.         access.release();
  22.  
  23.         return singleton;
  24.     }
  25.  
  26.     @Override
  27.     public void run() {
  28.         try {
  29.             getInstance();
  30.         } catch (InterruptedException e) {
  31.             e.printStackTrace();
  32.         }
  33.     }
  34.  
  35.     public static void main(String[] args) {
  36.         // TODO: 3/29/20 Simulate the scenario when multiple threads call the method getInstance
  37.         List<Thread> threads = new ArrayList<>();
  38.         for(int i=0;i<100;i++){
  39.             Singleton singleton = new Singleton();
  40.             threads.add(singleton);
  41.         }
  42.  
  43.         for(Thread t:threads){
  44.             t.run();
  45.         }
  46.  
  47.         System.out.println("Kreirana instanca: "+created);
  48.     }
  49.  
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement