Skip to content

Instantly share code, notes, and snippets.

@heanzyzabala
Last active August 24, 2020 08:37
Show Gist options
  • Save heanzyzabala/1e35fd27f2e1d0924d10baefa9ab8dd4 to your computer and use it in GitHub Desktop.
Save heanzyzabala/1e35fd27f2e1d0924d10baefa9ab8dd4 to your computer and use it in GitHub Desktop.
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;
}
}
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