Last active
August 24, 2020 08:37
-
-
Save heanzyzabala/1e35fd27f2e1d0924d10baefa9ab8dd4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MySingleton | |
{ | |
public static MySingleton mySingleton; | |
public static synchronized MySingleton getInstance(String tname) { | |
if(mySingleton == null) { | |
System.out.println("Thread " + tname + " Singleton class is null, instantiate and return the instance"); | |
mySingleton = new MySingleton(); | |
} | |
else { | |
System.out.println("Thread " + tname + " Singleton class is not null, returning the instance"); | |
} | |
return mySingleton; | |
} | |
public static MySingleton getInstance(String tname) { | |
if(mySingleton == null) { | |
System.out.println("Thread " + tname + " Singleton class is null, instantiate and return the instance"); | |
mySingleton = new MySingleton(); | |
} | |
else { | |
System.out.println("Thread " + tname + " Singleton class is not null, returning the instance"); | |
} | |
return mySingleton; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class SingletonMultipleThreadsMain | |
{ | |
public static void main(String[] args) { | |
for(int n=0; n<5; n++) { | |
MyThread myThread = new MyThread(); | |
myThread.setName(String.valueOf(n)); | |
myThread.start(); | |
} | |
} | |
static class MyThread extends Thread | |
{ | |
public MyThread() {} | |
@Override | |
public void run() { | |
System.out.println("Thread " + this.getName() + " has started "); | |
MySingleton.getInstance(this.getName()); | |
System.out.println("Thread " + this.getName() + " endend "); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment