Java Learning Lesson 25th (Multi-threaded (iv))-multithreading issues involved in a single-case design pattern

Source: Internet
Author: User

A single example design mode under multi-thread


Using the form of double judgement to solve the problem of lazy-type safety and efficiency

A hungry man-/*class single{private static final single t = new single ();p rivate single () {}public static single getinstance () {Retu RN 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)//Resolve security Issue {if (t==null) T = new single ();}} return t;}}

so the development is still the application of a hungry man style, but in the interview to examine the lazy type, because of its high technical content


Ii. Examples of deadlocks

Deadlocks: Common is, synchronous nesting

In the interview, it will let the writing deadlock program, as long as the written out, it means 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 ();p ublic static Final Object b_lock = new Object ();} Class Main{public static void Main (string[] args) {Deadlock T1 = new Deadlock (true);D eadlock t2 = new Deadlock (false); Thread J1 = new Thread (t1); Thread J2 = new Thread (t2); J1.start (); J2.start ();}}

If...alock
Else...block

It's locked, Thread-0 a lock,Thread-1 B lock .



Java Learning Lesson 25th (Multi-threaded (iv))-multithreading issues involved in a single-case design pattern

Related Article

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.