Java multi-thread (2) multi-thread lock mechanism and java multi-thread lock mechanism

Source: Internet
Author: User
Tags rounds

Java multi-thread (2) multi-thread lock mechanism and java multi-thread lock mechanism

When two threads access a class at the same time, some problems may occur. Concurrent thread re-entry may cause memory leakage, uncontrollable program, and so on. Both inter-thread communication and thread-shared data require the use of Java lock mechanism to control the problems caused by concurrent code. This article summarizes the famous Java lock mechanism and explains how to use the lock mechanism for concurrent thread communication under multithreading.

1. program exceptions under concurrency

Let's take a look at the following two codes to view the exception content.

Exception 1: Singleton Mode

1 package com. scl. thread; 2 3 public class SingletonException 4 {5 public static void main (String [] args) 6 {7 // enable ten threads to test the hashCode of the output class respectively, test whether to apply for the same class 8 for (int I = 0; I <10; I ++) 9 {10 new Thread (new Runnable () 11 {12 @ Override13 public void run () 14 {15 try16 {17 Thread. sleep (100); 18} 19 catch (InterruptedException e) 20 {21 e. printStackTrace (); 22} 23 System. out. println (Thread. currentThread (). getName () + "" + MySingle. getInstance (). hashCode (); 24} 25 }). start (); 26} 27} 28} 29 30 class MySingle31 {32 private static MySingle mySingle = null; 33 34 private MySingle () 35 {36} 37 38 public static MySingle getInstance () 39 {40 if (mySingle = null) {mySingle = new MySingle () ;}41 return mySingle; 42} 43}View code

The running result is as follows:

As can be seen from the above, Thread-7 is inconsistent with other results, proving that this Singleton writing has a problem in the case of multi-Thread concurrency, and the problem lies in 40th rows. Multiple Threads enter the null value judgment at the same time, and the thread creates a new class.

Exception 2: thread re-entry, causing a program error

Now we want to simulate the production rules of State-owned enterprises, produce 100 products each month, and then consume 20 products each month. Simulate annual production and sales of the Plant

Note: This example paves the way for the subsequent semaphores and producer and consumer issues. Another example can be provided. For example, if ten threads are opened, the tasks in each thread are accumulated from 1 to 10. The output result of each thread is not necessarily 55 (due to thread re-import)

1 package com. scl. thread; 2 3 // 100 products are produced each time, 20 products are consumed each time, and 12 rounds of 4 public class ThreadCommunicateCopy 5 {6 public static void main (String [] args) are replaced during production and consumption) 7 {8 final FactoryCopy factory = new FactoryCopy (); 9 new Thread (new Runnable () 10 {11 12 @ Override13 public void run () 14 {15 try16 {17 Thread. sleep (2000); 18} 19 catch (InterruptedException e) 20 {21 e. printStackTrace (); 22} 23 24 for (int I = 1; I <= 12; I ++) 25 {26 factory. createProduct (I); 27} 28 29} 30 }). start (); 31 32 new Thread (new Runnable () 33 {34 35 @ Override36 public void run () 37 {38 try39 {40 Thread. sleep (2000); 41} 42 catch (InterruptedException e) 43 {44 e. printStackTrace (); 45} 46 47 for (int I = 1; I <= 12; I ++) 48 {49 factory. sellProduct (I); 50} 51 52} 53 }). start (); 54 55} 56} 57 58 class FactoryCopy59 {60 // production product 61 public void createProduct (int I) 62 {63 64 for (int j = 1; j <= 100; j ++) 65 {66 System. out. println ("+" + I + ", "+ j + ""); 67} 68} 69 // sales product 70 public void sellProduct (int I) 71 {72 for (int j = 1; j <= 20; j ++) 73 {74 System. out. println ("no." + I + "sales, sales" + j + "pieces"); 75} 76 77} 78}View Code

The result is as follows:

This result cannot separate the codes of the sales thread and the production thread if necessary. Java locks can be used. The following describes how to deal with the above two problems.

 

2. multi-threaded programming and some basic knowledge of Java Multithreading

The use of Multithreading is nothing more than the expectation that the program can complete the task faster, so that concurrent programming must complete two things: thread synchronization and thread communication.

Thread Synchronization refers to controlling the order in which different threads occur.

Thread communication refers to how different threads share data.

Java thread Memory Model: Each thread has its own stack, and heap memory sharing [Source: Java concurrent programming art], as shown in. The lock is the carrier of memory and information communication between threads. To understand inter-thread communication, you will have a deeper understanding of the thread lock. We will also summarize in detail how Java communicates between two threads Based on the lock information.

2. Use the Java Lock Mechanism

Java speech design, like databases, also has code locks. It is relatively simple to implement Java code locks. Generally, two keywords are used to lock the code in a thread. The most common ones are volatile and synchronized.

2.1 synchronized

The Code modified by the synchronized keyword is equivalent to the mutex lock on the database. Make sure that multiple threads can only be in the method or synchronization block by one thread at the same time. Make sure that the thread is visible to and exclusive to the variable access. After the code ends, the lock is released.

Synchronzied can be used in two ways: ① locking the method above the method, and ② defining the synchronized block.

Simulate the production and sales cycle, and control Thread Synchronization Through the synchronized keyword. The Code is as follows:

1 package com. scl. thread; 2 3 // 100 products are produced each time, 20 products are consumed each time, 10 rounds of 4 public class ThreadCommunicate 5 {6 public static void main (String [] args) are replaced during production and consumption) 7 {8 final FactoryCopy factory = new FactoryCopy (); 9 new Thread (new Runnable () 10 {11 12 @ Override 13 public void run () 14 {15 try 16 {17 Thread. sleep (2000); 18} 19 catch (InterruptedException e) 20 {21 e. printStackTrace (); 22} 23 24 for (int I = 1; I <= 12; I ++) 25 {26 factory. createProduct (I); 27} 28 29} 30 }). start (); 31 32 new Thread (new Runnable () 33 {34 35 @ Override 36 public void run () 37 {38 try 39 {40 Thread. sleep (2000); 41} 42 catch (InterruptedException e) 43 {44 e. printStackTrace (); 45} 46 47 for (int I = 1; I <= 12; I ++) 48 {49 factory. sellProduct (I); 50} 51 52} 53 }). start (); 54 55} 56} 57 58 class Factory 59 {60 pr Ivate boolean isCreate = true; 61 62 public synchronized void createProduct (int I) 63 {64 while (! IsCreate) 65 {66 try 67 {68 this. wait (); 69} 70 catch (InterruptedException e) 71 {72 e. printStackTrace (); 73} 74} 75 76 for (int j = 1; j <= 100; j ++) 77 {78 System. out. println ("+" + I + ", "+ j + ""); 79} 80 isCreate = false; 81 this. notify (); 82} 83 84 public synchronized void sellProduct (int I) 85 {86 while (isCreate) 87 {88 try 89 {90 this. wait (); 91} 92 catch (InterruptedException e) 93 {94 e. printStackTrace (); 95} 96} 97 for (int j = 1; j <= 20; j ++) 98 {99 System. out. println ("" + I + "," + j + ""); 100} 101 isCreate = true; 102 this. notify (); 103} 104}View Code

 

The above Code uses the synchronized keyword to control the production and sales methods. Only one thread can enter each time. The isCreate flag is used in the code to control the order of production and sales.

Note: The synchronized modifier is used by default. The keyword uses the current instance object as the Lock Object to lock the thread.

You can add the synchronized keyword to the getInstance mode to modify the singleton mode.

The wait and notify methods will be explained in the thread summary in article 3.

2.2 volatile

Volatile keywords are mainly used to modify variables. Unlike synchronized, they can block code locks. This keyword can be seen as a synchronization operation for reading or writing modified variables.

Run the following code:

1 package com. scl. thread; 2 3 public class NumberRange 4 {5 private volatile int unSafeNum; 6 7 public int getUnSafeNum () 8 {9 return unSafeNum; 10} 11 12 public void setUnSafeNum (int unSafeNum) 13 {14 this. unSafeNum = unSafeNum; 15} 16 17 public int addVersion () 18 {19 return this. unSafeNum ++; 20} 21}View Code

The function after code compilation is as follows:

1 package com. scl. thread; 2 3 public class NumberRange 4 {5 private volatile int unSafeNum; 6 7 public synchronized int getUnSafeNum () 8 {9 return unSafeNum; 10} 11 12 public synchronized void setUnSafeNum (int unSafeNum) 13 {14 this. unSafeNum = unSafeNum; 15} 16 17 public int addVersion () 18 {19 int temp = getUnSafeNum (); 20 temp = temp + 1; 21 setUnSafeNum (temp); 22 return temp; 23} 24 25}View Code

It can be seen that when the volatile variable is used for auto-increment or auto-increment operations, when the variable is in the temp = temp + 1 step, multiple threads may simultaneously operate on this code, cause content to go on a business trip. The atomicity in the thread code is damaged.

 

The above is a summary of the Java lock mechanism. If there is any problem, please point out the correct. For a large part of the code and examples, refer to Java concurrent programming art.

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.