Java tread Multithreading (2) Multithreading security issues

Source: Internet
Author: User

Author: Ching

Original address: http://blog.csdn.net/qingdujun/article/details/39348093


This article demonstrates, tread multithreading security issues, and several ways to troubleshoot multithreading security (thread synchronization).

1) A thread unsafe demo

2) thread synchronization (synchronized, function synchronization, this lock, class object lock )


A small demo demo leads to thread safety issues:

Package THREAD.RUNABLE1.QDJ;//1. Defines the class implementation Runnable interface class RUNDEMO1 implements runnable{private int x = 5;//2. Overwrite the Run method in the Runnable interface//to store the thread code in run public void run () {while (true) {if (x > 0) {//Join sleep (), note: Sleep () throws an exception try { Thread.Sleep (ten);  Let the thread Sleep 10ms} catch (Exception e) {e.printstacktrace ();} System.out.println ("Runnable:" +x);--x;}}} public class CRunableDemo1 {public static void main (string[] args) {RunDemo1 r = new RunDemo1 ()//3. Thread objects are established through the thread class and Runn The subclass object of the able interface is the parameter thread t1 = new Thread (r); Thread t2 = new Thread (r); thread t3 = new Thread (r); thread T4 = new Thread (r),//4. Using start to open thread T1.start (); T2.start (); T3.start (); T4.start ();}}

To perform the displayed results:


The above print out the numbers such as 0,-1,-2. Did you find it? (There's a problem with threading!)

!!

)
Question: What is the solution to the problem?

Explanation: Thread 1 entered, forced to sleep 10ms. At this point, thread 2 enters, and force sleep 10ms; thread 3 enters and forces sleep 10ms. Thread 4 into the forced sleep 10ms;

Note that the above 4 threads sleep have entered the IF statement, when entering the time x>0 is still established;

All right. Thread 1 wakes up and starts printing print 5,4,3,2, when--x is not running yet. Thread 2 woke up. Rob the CPU of the right to run ......... .....


Second, thread synchronization

Question: Can we take one of these measures for the above question? When thread 1 runs the run code snippet. We do not allow other threads to run until thread 1 runs out, and the rest of the thread is able to enter.

Workaround: Fortunately, Java has this function. Wrap up the code snippet. will be able to achieve the above problem descriptive narrative effect.

Function name: synchronized, need a number of parameters. Just pass a random object on the OK (detailed parameter difference analysis. Please pull down to Appendix 1).

1) A simple way to solve the problem:

Package THREAD.RUNABLE1.QDJ;//1. Define class implementation Runnable interface class RUNDEMO1 implements runnable{private int x = 5;object obj = new Objec T ();//2. Overwrite the Run method in the Runnable interface//store the thread code in run public void run () {while (true) {synchronized (obj) {if (x > 0) {//Join sleep (). Note: Sleep () throws an exception to try {Thread.Sleep (ten);  Let the thread Sleep 10ms} catch (Exception e) {e.printstacktrace ();} System.out.println ("Runnable:" +x);--x;}}}} public class CRunableDemo1 {public static void main (string[] args) {RunDemo1 r = new RunDemo1 ()//3. Thread objects are established through the thread class and Runn The subclass object of the able interface is the parameter thread t1 = new Thread (r); Thread t2 = new Thread (r); thread t3 = new Thread (r); thread T4 = new Thread (r),//4. Using start to open thread T1.start (); T2.start (); T3.start (); T4.start ();}}
The execution results show:


2) A simpler solution: function synchronization (add synchronized directly in front of the function)

Description: Did you find that the function is to package multiple statements? However, the function is only packaged. Instead of synchronizing like the synchronized above. But there is a way to achieve this effect. Look at the following small demo is clear.

Package thread.runable1.qdj;//sync function class Synfunc {private int x = 5;public synchronized void Afunc () {while (true) {if (x ; 0) {//Join sleep (), note: Sleep () throws an exception to try {Thread.Sleep (ten);  Let the thread Sleep 10ms} catch (Exception e) {e.printstacktrace ();} System.out.println ("Runnable:" +x);--x;}}} 1. Define class implementation Runnable interface class RunDemo1 implements runnable{private synfunc syn = new Synfunc ()//2. Overwrite the Run method in the Runnable interface// Store thread code in run public void run () {Syn.afunc ();}} public class CRunableDemo1 {public static void main (string[] args) {RunDemo1 r = new RunDemo1 ()//3. Thread objects are established through the thread class and Runn The subclass object of the able interface is the parameter thread t1 = new Thread (r); Thread t2 = new Thread (r); thread t3 = new Thread (r); thread T4 = new Thread (r),//4. Using start to open thread T1.start (); T2.start (); T3.start (); T4.start ();}}
Execution Results display: (IBID.)


Appendix 1: Interpretation of the parameters of synchronized in a function lock (let's take a look at the following small demo)

Package THREAD.RUNABLE1.QDJ;//1. Define class implementation Runnable interface class RUNDEMO1 implements runnable{private int x = 100;object obj = new obj ECT (); Boolean flag = True;//2. Overwrite the Run method in the Runnable interface//store the thread code in run public void run () {if (flag) {while (true) {synchronized (  obj) {if (x > 0) {//Join sleep (), note: Sleep () throws an exception to try {Thread.Sleep (10); Let the thread Sleep 10ms} catch (Exception e) {e.printstacktrace ();} System.out.println ("Runnable:" +x);--x;}}} else {while (true) Afunc ();}}  Public synchronized void Afunc () {while (true) {if (x > 0) {//Join sleep (), note: Sleep () throws an exception to try {Thread.Sleep (10); Let the thread Sleep 10ms} catch (Exception e) {e.printstacktrace ();} System.out.println ("Runnable:" +x);--x;}}} public class CRunableDemo1 {public static void main (string[] args) {RunDemo1 r = new RunDemo1 ();//3. The thread object is established through the thread class. And the subclass object of the Runnable interface as the parameter thread T1 = new Thread (r); Thread t2 = new Thread (r);//4. Use start to open thread T1.start ();//Join Sleep ().  Note: Sleep () throws an exception to try {Thread.Sleep (10); Let the thread Sleep 10ms} catch (Exception e) {e.printstacktrace ();} R.flag = False;t2.start ();}}
To perform the displayed results:



Depressed bar, there is a thread safety problem, but we clearly have to add a lock ah? What is the cause of this? In fact, the problem is. the number of synchronized inside.

Function synchronization Lock is this, and the above small demo inside, one is the function of synchronous lock (this), the other is the obj lock, found? Workaround: Changing the obj lock to this lock is no problem.

Small demo after the solution:

Package THREAD.RUNABLE1.QDJ;//1. Define class implementation Runnable interface class RUNDEMO1 implements runnable{private int x = 100;object obj = new obj ECT (); Boolean flag = True;//2. Overwrite the Run method in the Runnable interface//store the thread code in run public void run () {if (flag) {while (true) {synchronized (  This) {if (x > 0) {//Join sleep (), note: Sleep () throws an exception to try {Thread.Sleep (10); Let the thread Sleep 10ms} catch (Exception e) {e.printstacktrace ();} System.out.println ("Runnable:" +x);--x;}}} else {while (true) Afunc ();}}  Public synchronized void Afunc () {while (true) {if (x > 0) {//Join sleep (), note: Sleep () throws an exception to try {Thread.Sleep (10); Let the thread Sleep 10ms} catch (Exception e) {e.printstacktrace ();} System.out.println ("Runnable:" +x);--x;}}} public class CRunableDemo1 {public static void main (string[] args) {RunDemo1 r = new RunDemo1 ()//3. Thread objects are established through the thread class and Runn The subclass object of the able interface is the parameter thread t1 = new Thread (r); Thread t2 = new Thread (r);//4. Use start to open thread T1.start ();//Join Sleep ().  Note: Sleep () throws an exception to try {Thread.Sleep (10); Let the thread Sleep 10ms} catch (Exception e) {e.printstacktrace ();} R.flag = False;t2.start ();}}
To perform the displayed results:



Appendix 2: Ask another question, since the function is locked by this, so how do you explain the function as follows? Static function does not have this, how to lock?

public static synchronized void Afunc () {while (true) {if (x > 0) {//Join sleep (), note: Sleep () throws an exception to try {Thread.Sleep (ten);  Let the thread Sleep 10ms} catch (Exception e) {e.printstacktrace ();} System.out.println ("Runnable:" +x);--x;}}
Workaround: Static function, is a class function called by the class.

In fact, the lock of the static function here is the class object. Note the following for example the synchronized in the following small demo .

Small demo after the solution:

Package THREAD.RUNABLE1.QDJ;//1. Define class implementation Runnable interface class RUNDEMO1 implements runnable{private static int x = 100;boolean Flag = TRUE;//2. Overwrite the Run method in the Runnable interface//store the thread code in run public void run () {if (flag) {while (true) {synchronized (  Rundemo1.class) {if (x > 0) {//Join sleep (), note: Sleep () throws an exception to try {Thread.Sleep (10); Let the thread Sleep 10ms} catch (Exception e) {e.printstacktrace ();} System.out.println ("Runnable:" +x);--x;}}} else {while (true) Afunc ();}}  public static synchronized void Afunc () {while (true) {if (x > 0) {//Join sleep (), note: Sleep () throws an exception to try {Thread.Sleep (10); Let the thread Sleep 10ms} catch (Exception e) {e.printstacktrace ();} System.out.println ("Runnable:" +x);--x;}}} public class CRunableDemo1 {public static void main (string[] args) {RunDemo1 r = new RunDemo1 ();//3. The thread object is established through the thread class. And the subclass object of the Runnable interface as the parameter thread T1 = new Thread (r);  Thread t2 = new Thread (r),//4. Use start to open thread T1.start ();//Join Sleep (), note: Sleep () throws an exception try {thread.sleep (10); Let the thread Sleep 10ms} catch (Exception e) {e.printstacktrace ();} R.flag = False;t2.start ();}}

Execution display Result: (IBID.)


References: Java video Bi Xiangdong presenter

Original address: http://blog.csdn.net/qingdujun/article/details/39348093


Java tread Multithreading (2) Multithreading security issues

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.