Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.List;
- import java.util.concurrent.Semaphore;
- public class Singleton extends Thread{
- private static volatile Singleton singleton;
- static Semaphore access=new Semaphore(1);
- static int count=0;
- static int created=0;
- private Singleton() {}
- public static Singleton getInstance() throws InterruptedException {
- // TODO: 3/29/20 Synchronize this
- access.acquire();
- count++;
- if(count==1){
- singleton = new Singleton();
- created++;
- }
- access.release();
- return singleton;
- }
- @Override
- public void run() {
- try {
- getInstance();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- public static void main(String[] args) {
- // TODO: 3/29/20 Simulate the scenario when multiple threads call the method getInstance
- List<Thread> threads = new ArrayList<>();
- for(int i=0;i<100;i++){
- Singleton singleton = new Singleton();
- threads.add(singleton);
- }
- for(Thread t:threads){
- t.run();
- }
- System.out.println("Kreirana instanca: "+created);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement