Dark Horse Programmer-Learning Diary (multithreading security issues and deadlock awareness)

Source: Internet
Author: User
Tags ticket

------Java Training, Android training, iOS training, and looking forward to communicating with you! -------

Reasons for security issues:

When multiple code statements operate on the same shared data, one thread executes only a portion of the multiple statements, not finished, and another thread participates in the execution. The error that caused the shared data.

Class MLPC implements Runnable{    private int ticket =;        {        while (true)        {            if (ticket>0)            {                try {thread.sleep (); Let the thread enter the frozen state} catch (Exception e) {} System.out.println (Thread.CurrentThread () + "" +ticket--);}}} Class Mlpcdemo {public static voidMLPC m = new MLPC (); Thread th0 = new thread (m); Thread Th1 = new thread (m); Thread Th2 = new thread (m); Thread th3 = new thread (m); Th0.start (); Th1.start (); Th2.start (); Th3.start ()    ;}} 

The results of the votes of-1 and-2 appeared.

Workaround:

For multiple threads to manipulate the statement that shares the data, you can only have one thread complete at a time. During execution, other threads are not allowed to participate in execution.

Way:

Synchronizing code blocks:

Class MLPC implements Runnable{    private int ticket =;    Object obj = new object ();        {While        (true)        {            synchronized (obj) {if (ticket>0) {try {thread.sleep ( ); } catch (Exception e) {} System.out.println (Thread.CurrentThread () + "" +ticket--);   }}}} 

The object is like a lock, and the thread holding the lock can execute in the synchronization. A thread that does not hold a lock, even if it gets the execution of the CPU, cannot get in because the lock is not acquired.

Prerequisites for synchronization:

1. Must have two or more than two threads

2. Multiple threads must use the same lock. You must ensure that only one thread in the synchronization is running.

Benefit: resolves thread security issues

Cons: Consumes resources, multiple threads need to determine the lock.

Two depositors deposited 300 yuan to the bank, each 100 and deposited 3 times.

Find out the security issues of the program change.

1, make clear what code is multithreaded to run the code.

2, clear sharing of data

3, clear which statements in multithreaded run code are operations that share data.

We created 4 threads, which, unlike before, used synchronous functions and synchronized code quickly. See how it turns out.

classMlpcImplementsrunnable{Private intTicket = 550;  Public BooleanFlag =true; Object obj=NewObject ();  Public voidrun () {if(Flag = =true)        {             while(true)            {                synchronized (obj) {if(ticket>0)                   {                          Try{Thread.Sleep (20); }                      Catch(Exception e) {} System.out.println (thread.currentthr EAD ()+ "Show" +ticket--); }                  }            }        }        Else        {             while(true) {show (); }        }    }    Public   synchronized void  Show () {if(ticket>0)            {                    Try{Thread.Sleep (20); }                Catch(Exception e) {} System.out.println (Thread.CurrentThread ()+ "Show" +ticket--); }     }} classMlpcdemo { Public Static voidMain (string[] args) {MLPC m=NewMLPC (); Thread Th0=NewThread (m); Thread Th1=NewThread (m); Thread Th2=NewThread (m); Thread Th3=NewThread (m);        Th0.start (); Try{Thread.Sleep (20); }        Catch(Exception e) {} M.flag=false;        Th1.start ();        Th2.start ();    Th3.start (); }}

The result was a vote of 0.

  Public voidrun () {if(Flag = =true)        {             while(true)            {                synchronized (  This)//change from the original arbitrary object to a functionthe object to which you belongThis  
{ if(ticket>0) { Try{Thread.Sleep (20); } Catch(Exception e) {} System.out.println (Thread.curr Entthread ()+ "Show" +ticket--); } } } } Else { while(true) {show (); } } }

Now, in any case, the normal results are displayed. This verifies that the function has the object it belongs to, so the synchronization function uses this lock.

Deadlock:

Deadlocks can occur when there are multiple different locks in the class, and these locks intersect

Such as:

1, Lock a--11

{Lock B--22}

2, Lock b--33

{Lock a--44}

A cross-over lock appears like above. If 11 33 is executed at the same time to run 22 44 is locked. 22 was locked under B, and 44 was locked by the above 11. Then we can't do it anymore.

classDemoImplementsrunnable{Private BooleanFlag; Demo (Booleanflag) {         This. Flag =Flag; }     Public voidrun () {if(flag) { while(true)            synchronized(Mylock.locka) {System.out.println ("If Locka"); synchronized(mylock.lockb) {System.out.println ("If lockb"); }            }        }        Else        {             while(true)                        synchronized(mylock.lockb) {System.out.println ("Else lockb"); synchronized(Mylock.locka) {System.out.println ("Else Locka"); }            }        }    }}classmylock{StaticObject Locka =NewObject (); StaticObject lockb =NewObject ();} classThreadTest { Public Static voidMain (string[] args) {Thread T1=NewThread (NewDemo (true)); Thread T2=NewThread (NewDemo (false));        T1.start (); Try{Thread.Sleep (100); }        Catch(Exception e) {} t2.start (); }}

Producer and consumer issues:

1 classPcdemo 2{3 public static voidMain (string[] args) 4{5 Resource R = newResource (); 6 Producer PRD = newProducer (R); 7 Consumer CSU = newConsumer (R); 8 9 Thread Th0 = newThread (PRD), ten thread th1 = newThread (PRD); Thread Th2 = newThread (PRD); thread th3 = newThread (PRD); thread Th4 = newThread (CSU); th5 = newThread (CSU); thread Th6 = newThread (CSU); th7 = newThread (CSU); 18Th0.start (); 19Th1.start (); 20Th2.start (); 21Th3.start (); 22Th4.start (); 23Th5.start (); 24Th6.start (); 25Th7.start (); 26}27}28 classResource31{PrivateString name;33 private int Count =1; private Boolean flag = False; public synchronized voidSet (String name) 37{if(flag) Try40{41Wait (); 42}43 catch(Exception e) 44{45}46 this.name = name+ "---" +count++; System.out.println (Thread.CurrentThread (). GetName () + "produce" +this. name); flag = True;. notify (); 50}51 public synchronized VoidOut () 52{if (!Flag) try55{56Wait (); 57}58 catch(Exception e) 59 {}61 System.out.println (Thread.CurrentThread (). GetName () + "________ consumption" +this . Name); False ;}65 this . Notify (); (+) }67 Producer implements  Runnable69  {priv Ate  Resource res;71  Producer (Resource res) $  {this.res =  res;74 }75 public void  Run ()  {Res.set (true ) +  ("Object" ), + }81 }82 }83-Class Consumer Implements  Runnable85  {Resource private  res;87  Consumer (Resource res)-- {this.res =  res;90 }91 public void  Run () () () () () () () () () () [{] * * * (True ) 94  {}9  res.out (); 7 }98}                

If only two threads are turned on, the runtime will rotate "consumption-production" in harmony. But if you open two threads each, this will happen.

T1 to obtain the qualification, execution rights, production of goods 1, the flag is true after the T1 into the blocking state, T2 access to the status of eligibility and execution of the blocking state, T3 to obtain the eligibility and enforcement rights, consumer goods 1-> wake the first to enter the thread pool T1, T3 and then blocked, T1 to qualify, if the same qualification T4 grab execution rights->t4 congestion->t1 get execution rights--production goods 2-> Wake T2, T2 get execution right no longer judge flag true and false direct production T3.

Then change the if judgment to a while loop, which does make up for the error. But will cause T2 "wake up", Judge flag true and false->t2 into the blocking state. Causes all threads to wait all the while. Use Notifyall () and always wake up all threads. Solved the problem once again.

JDK1.5 provides a multi-threaded upgrade solution that replaces the synchronous synchronized with a real lock operation to obtain a Condition instance for a particular Lock instance, using its newcondition () method.

The Condition instance is essentially bound to a lock. Condition the object Monitor method (wait, notify, and Notifyall) into distinct objects,

In order to use these objects in combination with any Lock implementation.

Dark Horse Programmer-Learning Diary (multithreading security issues and deadlock awareness)

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.