venerdì 16 marzo 2012
Singleton pattern
/**
* Test client class for Singleton
* @author bacco
*
*/
public class SingletonClientClass implements Runnable {
MySingletonClass singleton = MySingletonClass.getInstance();
public static void main (String [] args){
SingletonClientClass clinetClass = new SingletonClientClass();
Thread t1 = new Thread(clinetClass);
t1.setName("Thread1");
Thread t2 = new Thread(clinetClass);
t1.setName("Thread2");
t1.start();
t2.start();
}
@Override
public void run() {
long init = System.currentTimeMillis();
System.out.println (System.currentTimeMillis() - init);
System.out.println( Thread.currentThread().getName() + "setting name ");
singleton.setName(Thread.currentThread().getName());
for (int i =0; i < 5 ; i++) {
try {
System.out.println (System.currentTimeMillis() - init );
System.out.println (Thread.currentThread().getName() + "stopping ");
Thread.currentThread().sleep(3000);
System.out.println (System.currentTimeMillis() - init);
System.out.println (Thread.currentThread().getName() + "setting name");
singleton.setName(Thread.currentThread().getName());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated method stub
}
}
}
/**
* Singleton class
* @author bacco
*
*/
class MySingletonClass {
private static MySingletonClass instance;
private String name;
/*
* serve ad inibire il costruttore
*/
private MySingletonClass (){
}
public static synchronized MySingletonClass getInstance(){
if (instance == null ){
instance = new MySingletonClass();
}
return instance;
}
public synchronized void setName(String name) {
instance.name = name;
System.out.println("Singleton Instance " + this.toString() + " Named " + this.name );
}
}
Here sample output
0
0
Thread2setting name
Thread-1setting name
Singleton Instance MySingletonClass@6bbc4459 Named Thread2
2
Singleton Instance MySingletonClass@6bbc4459 Named Thread-1
1
Thread2stopping
Thread-1stopping
3002
3001
Thread-1setting name
Singleton Instance MySingletonClass@6bbc4459 Named Thread-1
3001
Thread-1stopping
Thread2setting name
Singleton Instance MySingletonClass@6bbc4459 Named Thread2
3002
Thread2stopping
6001
Thread-1setting name
Singleton Instance MySingletonClass@6bbc4459 Named Thread-1
6001
Thread-1stopping
6002
Thread2setting name
Singleton Instance MySingletonClass@6bbc4459 Named Thread2
6002
Thread2stopping
9002
9001
Thread-1setting name
Singleton Instance MySingletonClass@6bbc4459 Named Thread-1
Thread2setting name
Singleton Instance MySingletonClass@6bbc4459 Named Thread2
Iscriviti a:
Commenti sul post (Atom)
Nessun commento:
Posta un commento