未使用同步解决线程安全问题,并不是单例的,输出的两对象地址不相同
public class SingleTon {
public static void main(String[] args) {
CallableImpl callable = new CallableImpl();
CallableImpl callable1 = new CallableImpl();
FutureTask<Account> task = new FutureTask<Account>(callable);
FutureTask<Account> task1 = new FutureTask<Account>(callable1);
Thread thread = new Thread(task,"线程一");
Thread thread1 = new Thread(task1,"线程二");
thread.start();
thread1.start();
try {
Account account = task.get();
System.out.println("线程一返回结果:"+account);
Account account1 = task1.get();
System.out.println("线程二返回结果:"+account1);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
class Account{
private Account(){
}
private static Account instance = null;
public static Account getInstance(){
// if(instance == null){
// synchronized (Account.class){
if(instance == null){
instance = new Account();
}
// }
// }
return instance;
}
}
class CallableImpl implements Callable<Account> {
@Override
public Account call() throws Exception {
return Account.getInstance();
}
}
这是输出结果:
使用同步解决线程安全问题后,是单例的,输出的两对象地址相同
public class SingleTon {
public static void main(String[] args) {
CallableImpl callable = new CallableImpl();
CallableImpl callable1 = new CallableImpl();
FutureTask<Account> task = new FutureTask<Account>(callable);
FutureTask<Account> task1 = new FutureTask<Account>(callable1);
Thread thread = new Thread(task,"线程一");
Thread thread1 = new Thread(task1,"线程二");
thread.start();
thread1.start();
try {
Account account = task.get();
System.out.println("线程一返回结果:"+account);
Account account1 = task1.get();
System.out.println("线程二返回结果:"+account1);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
class Account{
private Account(){
}
private static Account instance = null;
public static Account getInstance(){
if(instance == null){
synchronized (Account.class){
if(instance == null){
instance = new Account();
}
}
}
return instance;
}
}
class CallableImpl implements Callable<Account> {
@Override
public Account call() throws Exception {
return Account.getInstance();
}
}
输出结果: