Java thread security

Source: Internet
Author: User

@ Thread:

Thread security: the so-called thread security means to control the orderly access and modification of a resource by multiple threads.
Methods To ensure thread security:
1.SynchronizedThe keyword is used to modify the method body or package code quickly to ensure that only one thread can operate in a multi-threaded environment before the result is returned.

Public synchronized void count () {} synchronized (lock) {code block}


2. VolatileKeyword is used to modify a field. Volatile ensures the visibility of internal data, that is, the master data is operated on each time.
         public volatile num = 0;

3. jdk-6 later provided LockObject.
Lock lock = new ReentrantLock (); public void count () {lock. lock (); // get the lock code block Lock. unlock ();}

The visibility mentioned above involves the java memory model. To solve the memory model, you must solve the visibility and orderliness issues.
Visibility: Data in the primary storage.
int num = 0;for(int i = 0;i<10;i++){   num+=1;}

In the above Code. Num and primary storage. When num + = 2 is executed, jvm first copies num from the primary storage.
The subsequent operations on num are in the Operation copy. To the last synchronization to the primary storage. Therefore, when the data is not synchronized to the primary storage, other threads
Accessing the num value in the primary storage is not the expected value. This is the visibility issue. Here we will throw such a problem:
"How to control the orderly access to data by multiple threads ?"
If the synchronization problem is not solved: A shared object can be operated by multiple threads at the same time, resulting in chaotic results. Taking deposit and withdrawal from a bank account as an example:

Package com. zhaofeng; public class Bank {private int balance; public Bank (int balance) {this. balance = balance;} public int getBalance () {return balance;} public void add (int num) {balance = balance + num;} public void out (int num) {balance = balance-num;} public static void main (String [] args) throws InterruptedException {Bank account = new Bank (1000 ); thread a = new Thread (new AddThread (account, 20000), "deposit"); Thread B = new Thread (new OutThread (account, 10000), "withdrawal");. start (); B. start ();. join (); B. join (); System. out. println (account. getBalance ();} static class AddThread implements Runnable {Bank account; int amount; public AddThread (Bank account, int amount) {this. account = account; this. amount = amount;} public void run () {for (int I = 0; I <amount; I ++) {account. add (1) ;}} static class OutThread implements Runnable {Bank account; int amount; public OutThread (Bank account, int amount) {this. account = account; this. amount = amount;} public void run () {for (int I = 0; I <amount; I ++) {account. out (1 );}}}}

The above Code does not use the synchronization mechanism. If you run the code multiple times, the program will produce different results. Therefore, multi-thread access to add () and out () is unpredictable. You need to use the synchronized keyword or other methods for the add () and out () functions.

 public synchronized void add(int num) {          balance = balance + num;      }        public synchronized void out(int num) {          balance = balance - num;      }  
This ensures the orderly access of multiple threads.


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.