JAVA course 25th (multithreading (IV)-multithreading problems involved in the singleton Design Model

Source: Internet
Author: User

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.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.