JAVA course 25th (multithreading (IV)-multithreading problems involved in the singleton Design Model
I. multi-threaded Singleton Design Mode
Uses the form of dual judgment to solve the security and efficiency problems in the lazy way.
// Hungry Chinese/* class Single {private static final Single t = new Single (); private Single () {} public static Single getInstance () {return t ;}} * // lazy class Single {private static Single t = null; private Single () {} public static Single getInstance () {if (t = null) // solve the efficiency problem {synchronized (Single. class) // solve the security problem {if (t = null) t = new Single () ;}} return t ;}}
Therefore, the development is still based on the hungry Chinese style, but the lazy Chinese style is investigated during the interview because of its high technical content.
Ii. deadlock example
Deadlock: Usually, synchronization nesting
During the interview, the deadlock program will be written. As long as it is written, it indicates that the deadlock has been understood.
class Deadlock implements Runnable{private boolean flag;public Deadlock(boolean flag) {// TODO Auto-generated constructor stubthis.flag = flag;}public void run(){if(flag){while(true)synchronized (lock.A_LOCK) {System.out.println("if...alock");synchronized (lock.B_LOCK) {System.out.println("if...block");}}}else {while(true)synchronized (lock.B_LOCK) {System.out.println("else...block");synchronized (lock.A_LOCK) {System.out.println("else...alock");}}}}}class lock{public static final Object A_LOCK = new Object();public static final Object B_LOCK = new Object();}class Main{public static void main(String[] args){Deadlock t1 = new Deadlock(true);Deadlock t2 = new Deadlock(false);Thread j1 = new Thread(t1);Thread j2 = new Thread(t2);j1.start(); j2.start();}}
If... alock
Else... block
Locked. Thread-0 gets the lock, and Thread-1 gets the B lock.