Java Tread multithreading (2) multithreading security issues

Source: Internet
Author: User

Java Tread multithreading (2) multithreading security issues

 

 

This article demonstrates the Tread multi-thread security problem and several multi-thread security methods (thread synchronization ).

1) A thread-safe Demo

2) thread synchronization (synchronized, function synchronization, this lock, Class Object lock)

 

I. the Demo introduces thread security issues:

 

Package thread. runable1.qdj; // 1. define class implementation Runnable interface class RunDemo1 implements Runnable {private int x = 5; // 2. override the run method in the Runnable interface // store the thread code in the run public void run () {while (true) {if (x> 0) {// Add sleep (), note: sleep () throws an exception. try {Thread. sleep (10); // sleep the thread for 10 ms} 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. create a Thread object through the Thread class, and take the subclass object of the Runnable interface as the parameter Thread t1 = new Thread (r); Thread t2 = new Thread (r ); thread t3 = new Thread (r); Thread t4 = new Thread (r); // 4. use start to enable the thread t1.start (); t2.start (); t3.start (); t4.start ();}}

 

Running result:

The numbers 0,-1, and-2 are printed? (The thread has a problem !!!)
Q: Why?

Explanation: thread 1 enters and sleep for 10 ms. Thread 2 enters and sleep for 10 ms. Thread 3 enters and sleep for 10 ms. Thread 4 enters and then sleep for 10 ms;

Note: When the above four threads sleep, the if statement is entered. When the thread goes into the sleep state, x> 0 is still true;

Well, thread 1 wakes up and starts printing 5, 4, 3, and 2. At this time -- x has not been executed, and thread 2 will wake up, the execution right of cpu is snatched .....................

 

Ii. Thread Synchronization

Q: Can we take such measures for the above problems? When thread 1 executes the run code segment, we do not allow other threads to execute until thread 1 finishes executing.

Solution: Fortunately, there is such a function in Java. Wrap the code segment to achieve the effect described above. Function Name: synchronized. If you need a parameter, just upload an object. (For details about parameter differences, refer to Appendix 1 ).

1) A simple solution:

 

Package thread. runable1.qdj; // 1. define class implementation Runnable interface class RunDemo1 implements Runnable {private int x = 5; Object obj = new Object (); // 2. override the run method in the Runnable interface // store the thread code in the run public void run () {while (true) {synchronized (obj) {if (x> 0) {// Add sleep (). Note: sleep () throws an exception. try {Thread. sleep (10); // sleep the thread for 10 ms} 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. create a Thread object through the Thread class, and take the subclass object of the Runnable interface as the parameter Thread t1 = new Thread (r); Thread t2 = new Thread (r ); thread t3 = new Thread (r); Thread t4 = new Thread (r); // 4. use start to enable the thread t1.start (); t2.start (); t3.start (); t4.start ();}}
Running result display:

 

 

2) for a simpler solution: function synchronization (add synchronized directly before the function)

Note: Have you found that a function is used to package multiple statements? However, the function is only packaged and not synchronized like synchronized above. But there is a way to achieve this effect, you can see the following small Demo to understand.

 

Package thread. runable1.qdj; // synchronous function class SynFunc {private int x = 5; public synchronized void aFunc () {while (true) {if (x> 0) {// Add sleep (). Note: sleep () throws an exception. try {Thread. sleep (10); // sleep the thread for 10 ms} 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 the thread code in the run public void run () {syn. aFunc () ;}} public class CRunableDemo1 {public static void main (String [] args) {RunDemo1 r = new RunDemo1 (); // 3. create a Thread object through the Thread class, and take the subclass object of the Runnable interface as the parameter Thread t1 = new Thread (r); Thread t2 = new Thread (r ); thread t3 = new Thread (r); Thread t4 = new Thread (r); // 4. use start to enable the thread t1.start (); t2.start (); t3.start (); t4.start ();}}
Running result: (same as above)

 

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

 

Package thread. runable1.qdj; // 1. define class implementation Runnable interface class RunDemo1 implements Runnable {private int x = 100; Object obj = new Object (); boolean flag = true; // 2. override the run method in the Runnable interface // store the thread code in the run public void run () {if (flag) {while (true) {synchronized (obj) {if (x> 0) {// Add sleep (). Note: sleep () throws an exception. try {Thread. sleep (10); // sleep the thread for 10 ms} catch (Exception e) {e. printStackTrace ();} System. out. println (Runnable: + x); -- x ;}}} else {while (true) aFunc () ;}} public synchronized void aFunc () {while (true) {if (x> 0) {// Add sleep (). Note: sleep () throws an exception. try {Thread. sleep (10); // sleep the thread for 10 ms} 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. create a Thread object through the Thread class, and take the subclass object of the Runnable interface as the parameter Thread t1 = new Thread (r); Thread t2 = new Thread (r); // 4. use start to enable Thread t1.start (); // Add sleep (). Note: sleep () throws an exception. try {Thread. sleep (10); // sleep the thread for 10 ms} catch (Exception e) {e. printStackTrace ();} r. flag = false; t2.start ();}}
Running result:

 


 

Depressed, there is another thread security problem, but we have all added locks? What causes this? In fact, the problem lies in the parameters in synchronized.

Function synchronization locks this, while in the above Demo, one is the function synchronization lock (this) and the other is the obj lock. Did you find it? Solution: Change the obj lock to the this lock.

Demo after solution:

 

Package thread. runable1.qdj; // 1. define class implementation Runnable interface class RunDemo1 implements Runnable {private int x = 100; Object obj = new Object (); boolean flag = true; // 2. override the run method in the Runnable interface // store the thread code in the run public void run () {if (flag) {while (true) {synchronized (this) {if (x> 0) {// Add sleep (). Note: sleep () throws an exception. try {Thread. sleep (10); // sleep the thread for 10 ms} catch (Exception e) {e. printStackTrace ();} System. out. println (Runnable: + x); -- x ;}}} else {while (true) aFunc () ;}} public synchronized void aFunc () {while (true) {if (x> 0) {// Add sleep (). Note: sleep () throws an exception. try {Thread. sleep (10); // sleep the thread for 10 ms} 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. create a Thread object through the Thread class, and take the subclass object of the Runnable interface as the parameter Thread t1 = new Thread (r); Thread t2 = new Thread (r); // 4. use start to enable Thread t1.start (); // Add sleep (). Note: sleep () throws an exception. try {Thread. sleep (10); // sleep the thread for 10 ms} catch (Exception e) {e. printStackTrace ();} r. flag = false; t2.start ();}}
Running result:

 


 

Appendix 2: Another question is raised. Since the function is locked for synchronization, how can we explain the following function? How can I lock a static function without this?

 

Public static synchronized void aFunc () {while (true) {if (x> 0) {// Add sleep (). Note: sleep () throws an exception. try {Thread. sleep (10); // sleep the thread for 10 ms} catch (Exception e) {e. printStackTrace ();} System. out. println (Runnable: + x); -- x ;}}}
Solution: static functions are called by classes. In fact, the lock of the static function is a Class object. See the synchronized parameters in the following Demo.

 

Demo after solution:

 

Package thread. runable1.qdj; // 1. define class implementation Runnable interface class RunDemo1 implements Runnable {private static int x = 100; boolean flag = true; // 2. override the run method in the Runnable interface // store the thread code in the run public void run () {if (flag) {while (true) {synchronized (RunDemo1.class) {if (x> 0) {// Add sleep (). Note: sleep () throws an exception. try {Thread. sleep (10); // sleep the thread for 10 ms} 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) {// Add sleep (). Note: sleep () throws an exception. try {Thread. sleep (10); // sleep the thread for 10 ms} 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. create a Thread object through the Thread class, and take the subclass object of the Runnable interface as the parameter Thread t1 = new Thread (r); Thread t2 = new Thread (r); // 4. use start to enable Thread t1.start (); // Add sleep (). Note: sleep () throws an exception. try {Thread. sleep (10); // sleep the thread for 10 ms} catch (Exception e) {e. printStackTrace ();} r. flag = false; t2.start ();}}

Running result: (same as above)

 

 

 

References: Lecture on Java video Bi Xiangdong

Address: http://blog.csdn.net/qingdujun/article/details/39348093

 

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.