public class InstanceTest {
private static InstanceTest instance = null;
[color=red]private final static Lock lock = new ReentrantLock();[/color] //多个线程要共用一个锁
private InstanceTest(){System.out.println("---------------------");}
public static InstanceTest getInstance(){
// synchronized (InstanceTest.class) {
// if(instance == null){
// instance = new InstanceTest();
// }
// }
//
lock.lock();
if(instance == null){
instance = new InstanceTest();
}
lock.unlock();
return instance;
}
/**
*
* @param args
*/
public static void main(String[] args) {
for(int i=0;i<50;i++){
new Thread(new Runnable() {
@Override
public void run() {
InstanceTest.getInstance();
}
}).start();
}
}
}
private static InstanceTest instance = null;
[color=red]private final static Lock lock = new ReentrantLock();[/color] //多个线程要共用一个锁
private InstanceTest(){System.out.println("---------------------");}
public static InstanceTest getInstance(){
// synchronized (InstanceTest.class) {
// if(instance == null){
// instance = new InstanceTest();
// }
// }
//
lock.lock();
if(instance == null){
instance = new InstanceTest();
}
lock.unlock();
return instance;
}
/**
*
* @param args
*/
public static void main(String[] args) {
for(int i=0;i<50;i++){
new Thread(new Runnable() {
@Override
public void run() {
InstanceTest.getInstance();
}
}).start();
}
}
}