public class BankTest { static Bank b = null; static Bank b1 = null; public static void main(String[] args) { Thread t = new Thread() { public void run() { b = Bank.getBank(); } }; Thread t1 = new Thread() { public void run() { b1 = Bank.getBank(); } }; t.start(); t1.start(); try { t.join(); } catch (InterruptedException e) { throw new RuntimeException(e); } try { t1.join(); } catch (InterruptedException e) { throw new RuntimeException(e); } System.out.println(b); System.out.println(b1); System.out.println(b == b1); } } class Bank { private Bank(){} private static Bank instance; //方式1 // public static synchronized Bank getBank() // { // if(instance == null) // { // try // { // Thread.sleep(5000); // } // catch (InterruptedException e) // { // throw new RuntimeException(e); // } // instance = new Bank(); // } // return instance; // } //方式2 // public static Bank getBank() // { // synchronized(Bank.class) // { // if(instance == null) // { // try // { // Thread.sleep(5000); // } // catch (InterruptedException e) // { // throw new RuntimeException(e); // } // instance = new Bank(); // } // } // return instance; // } public static Bank getBank() { if(instance == null) { synchronized (Bank.class) { if (instance == null) { try { Thread.sleep(5000); } catch (InterruptedException e) { throw new RuntimeException(e); } instance = new Bank(); } } } return instance; } }
public class BankTest
{
static Bank b = null;
static Bank b1 = null;
public static void main(String[] args)
{
Thread t = new Thread()
{
public void run()
{
b = Bank.getBank();
}
};
Thread t1 = new Thread()
{
public void run()
{
b1 = Bank.getBank();
}
};
t.start();
t1.start();
try
{
t.join();
}
catch (InterruptedException e)
{
throw new RuntimeException(e);
}
try
{
t1.join();
}
catch (InterruptedException e)
{
throw new RuntimeException(e);
}
System.out.println(b);
System.out.println(b1);
System.out.println(b == b1);
}
}class Bank
{
private Bank(){}
private static Bank instance;
//方式1
// public static synchronized Bank getBank()
// {
// if(instance == null)
// {
// try
// {
// Thread.sleep(5000);
// }
// catch (InterruptedException e)
// {
// throw new RuntimeException(e);
// }
// instance = new Bank();
// }
// return instance;
// }
//方式2
// public static Bank getBank()
// {
// synchronized(Bank.class)
// {
// if(instance == null)
// {
// try
// {
// Thread.sleep(5000);
// }
// catch (InterruptedException e)
// {
// throw new RuntimeException(e);
// }
// instance = new Bank();
// }
// }
// return instance;
// }
public static Bank getBank()
{
if(instance == null)
{
synchronized (Bank.class) {
if (instance == null) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
instance = new Bank();
}
}
}
return instance;
}
}
JAVA利用多线程锁机制实现银行账户存取款线程安全------JAVA
于 2023-05-05 16:00:04 首次发布