Java notes-about thread synchronization (7 synchronous methods) and java 7

Source: Internet
Author: User
Tags tools and utilities to domain

Java notes-about thread synchronization (7 synchronous methods) and java 7

Thread Synchronization (7 methods)

-- If you want To reprint this article, please indicate the reprint address "http://www.cnblogs.com/XHJT/p/3897440.html" thank you --

Why use synchronization?
Java allows multi-thread concurrency control. When multiple threads simultaneously operate on a shared resource variable (such as adding, deleting, modifying, and querying data ),
Data may be inaccurate and conflict with each other. Therefore, a synchronization lock is added to avoid being called by other threads before the thread completes the operation,
This ensures the uniqueness and accuracy of the variable.

 

1. Synchronization Method
There is also a method for modifying the synchronized keyword.
Because every java object has a built-in lock, when this keyword is used to modify the method,
Built-in locks protect the entire method. You must obtain the built-in lock before calling this method. Otherwise, the lock is blocked.


The Code is as follows:
Public synchronized void save (){}


Note: The synchronized keyword can also modify the static method. If you call this static method, the entire class will be locked.

 

2. synchronous code block
There are statement blocks modified by the synchronized keyword.
The statement block modified by this keyword is automatically added with a built-in lock to achieve synchronization.


The Code is as follows:
Synchronized (object ){
}


Note: synchronization is a highly open operation, so you should minimize the amount of synchronization content.
Generally, there is no need to synchronize the entire method. Use the synchronized code block to synchronize key code.

Code example:

Package com. xhj. thread;/*** use of thread synchronization ** @ author XIEHEJUN **/public class SynchronizedThread {class Bank {private int account = 100; public int getAccount () {return account;}/*** use the synchronization method to implement ** @ param money */public synchronized void save (int money) {account ++ = money ;} /*** implement with synchronous code block ** @ param money */public void save1 (int money) {synchronized (this) {account ++ = money ;}}} class NewThread implements Runnable {private Bank bank; public NewThread (Bank bank) {this. bank = bank ;}@ Override public void run () {for (int I = 0; I <10; I ++) {// bank. save1 (10); bank. save (10); System. out. println (I + "account balance:" + bank. getAccount () ;}}/ *** creates a thread and calls the internal class */public void useThread () {Bank bank Bank = new Bank (); newThread new_thread = new NewThread (bank); System. out. println ("Thread 1"); Thread thread1 = new Thread (new_thread); thread1.start (); System. out. println ("Thread 2"); Thread thread2 = new Thread (new_thread); thread2.start ();} public static void main (String [] args) {SynchronizedThread st = new SynchronizedThread (); st. useThread ();}}


3. Use special domain variables (volatile) for Thread Synchronization

A. The volatile keyword provides a lock-free mechanism for access to domain variables,
B. Modifying the domain using volatile is equivalent to telling the virtual machine that the domain may be updated by other threads,
C. Therefore, each time you use this field, you need to recalculate it instead of using the value in the register.
D. volatile does not provide any atomic operations, nor can it be used to modify final-type variables.

For example:
In the preceding example, you only need to add the volatile modifier before the account to implement thread synchronization.

Code example:

// Only the code to be modified is provided. The remaining code is added with the variable to be synchronized with the same class Bank {// volatile private volatile int account = 100; public int getAccount () {return account;} // synchronized public void save (int money) {account + = money ;}}


Note: The non-synchronization problem in multithreading mainly occurs in the reading and writing of the domain. If you want the domain to avoid this problem, you do not need to modify the method used to operate the domain.
Using the final domain, lock-protected domain and volatile domain can avoid non-synchronization issues.

4. Use the re-entry lock for Thread Synchronization

Added a java. util. concurrent package in JavaSE5.0 to support synchronization.
The ReentrantLock class is a reentrant and mutex Lock that implements the Lock interface,
It has the same basic behavior and semantics as synchronized and quickbi, and extends its capabilities.


Common ReenreantLock methods include:

ReentrantLock (): Creates a ReentrantLock instance.
Lock (): Get the lock
Unlock (): Release the lock
Note: ReentrantLock () also has a constructor that can create a fair lock. However, it is not recommended because it can greatly reduce the program running efficiency.

For example:
Based on the above example, the rewritten code is:

Code example:

// Only the code to be modified is provided. The remaining code is equivalent to the same class Bank {private int account = 100; // you need to declare this Lock private lock Lock = new ReentrantLock (); public int getAccount () {return account;} // synchronized public void save (int money) {lock. lock (); try {account + = money;} finally {lock. unlock ();}}}


Note: Selection of Lock objects and synchronized keywords:
A. You 'd better not use either of them. Use a mechanism provided by java. util. concurrent,
It can help users process all lock-related code.
B. If the synchronized keyword can meet your needs, use synchronized because it can simplify the code.
C. If you need more advanced functions, use the ReentrantLock class. Pay attention to releasing the lock in time. Otherwise, a deadlock will occur. Generally, the lock is released in finally code.

5. Use local variables for Thread Synchronization
If ThreadLocal is used to manage a variable, each thread that uses the variable obtains a copy of the variable,
Copies are independent of each other, so that each thread can modify its own variable copy without affecting other threads.

 

Common Methods for ThreadLocal classes

 

ThreadLocal (): Creates a local thread variable.
Get (): returns the value in the current thread copy of the local variable of this thread.
InitialValue (): returns the "Initial Value" of the current thread of the local variable of this thread"
Set (T value): set the value in the current thread copy of the local variable of this thread to value.

 

For example:
Based on the above example, the modified Code is:

Code example:

// Only change the Bank class. The remaining code is the same as the public class Bank {// use the ThreadLocal class to manage the shared variable account private static ThreadLocal <Integer> account = new ThreadLocal <Integer> () {@ Override protected Integer initialValue () {return 100 ;}}; public void save (int money) {account. set (account. get () + money);} public int getAccount () {return account. get ();}}

Note: ThreadLocal and synchronization mechanisms
A. ThreadLocal and synchronization mechanisms are designed to solve the access conflicts of the same variables in multiple threads.
B. The former adopts the "space for Time" method, and the latter adopts the "Time for space" method.

 

 

 

6. Use a blocking queue for Thread Synchronization

 

The first five Synchronization Methods are implemented at the underlying thread level, but we should try to stay away from the underlying structure during actual development.
Using the java. util. concurrent package added in javaSE5.0 helps simplify development.
This section mainly usesLinkedBlockingQueue <E>To synchronize threads.
LinkedBlockingQueue <E> is a blocking queue in any range based on connected nodes.
The queue is the first-in-first-out sequence (FIFO). The queue will be explained in detail later ~

LinkedBlockingQueue 
Define blockingqueue (): Create a volume blockingqueue with the capacity of Integer. MAX_VALUE
Put (E): Add an element at the end of the team. If the queue is full, it will be blocked.
Size (): returns the number of elements in the queue.
Take (): removes and returns the element of the queue header. If the queue is empty, it is blocked.

Code example: 
Synchronize commodity manufacturers and commodities

1 package com. xhj. thread; 2 3 import java. util. random; 4 import java. util. concurrent. linkedBlockingQueue; 5 6/** 7 * use a blocking queue to implement thread synchronization LinkedBlockingQueue. Use 8*9 * @ author XIEHEJUN10 * 11 */12 public class BlockingSynchronizedThread {13/** 14 * to define the blocking queue is used to store the produced product 15 */16 private blocks blockingqueue <Integer> queue = new blocks blockingqueue <Integer> (); 17/** 18 * define the number of production items 19 */20 private static final int size = 10; 21/** 22 * define the start thread flag. When it is 0, start the thread for producing the product. If the value is 1, the thread for consuming the product is 23 */24 private int flag = 0; 25 26 private class LinkBlockThread implements Runnable {27 @ Override28 public void run () {29 int new_flag = flag ++; 30 System. out. println ("Startup thread" + new_flag); 31 if (new_flag = 0) {32 for (int I = 0; I <size; I ++) {33 int B = new Random (). nextInt (255); 34 System. out. println ("product:" + B + "); 35 try {36 queue. put (B); 37} catch (InterruptedException e) {38 // TODO Auto-generated catch block39 e. printStackTrace (); 40} 41 System. out. println ("there are items in the repository:" + queue. size () + ""); 42 try {43 Thread. sleep (100); 44} catch (InterruptedException e) {45 // TODO Auto-generated catch block46 e. printStackTrace (); 47} 48} 49} else {50 for (int I = 0; I <size/2; I ++) {51 try {52 int n = queue. take (); 53 System. out. println ("purchased by the consumer" + n + "commodity"); 54} catch (InterruptedException e) {55 // TODO Auto-generated catch block56 e. printStackTrace (); 57} 58 System. out. println ("there are items in the repository:" + queue. size () + ""); 59 try {60 Thread. sleep (100); 61} catch (Exception e) {62 // TODO: handle exception63} 64} 65} 66} 67} 68 69 public static void main (String [] args) {70 BlockingSynchronizedThread bst = new BlockingSynchronizedThread (); 71 LinkBlockThread lbt = bst. new LinkBlockThread (); 72 Thread thread1 = new Thread (lbt); 73 Thread thread2 = new Thread (lbt); 74 thread1.start (); 75 thread2.start (); 76 77} 78 79}

 

Note: BlockingQueue <E> defines common methods for blocking queues, especially the three methods for adding elements. Note that when the queue is full:

The add () method throws an exception.

The offer () method returns false.

The put () method is blocked.

 

 

7. Use atomic variables for Thread Synchronization

 

The root cause of thread synchronization is that operations on common variables are not atomic.


So what is an atomic operation?
Atomic operation refers to reading the variable value, modifying the variable value, and saving the variable value as a whole.
That is, these actions are either completed at the same time or not completed.

In javaThe util. concurrent. atomic package provides a tool class for creating atomic type variables.,
This class can simplify thread synchronization.

WhereAtomicIntegerA table can update the int value in atomic mode and can be used in applications (such as counters added in atomic mode ),
However, it cannot be used to replace Integer; it can be expanded to allow uniform access by tools and utilities that handle the Number of opportunities.

Common AtomicInteger methods:
AtomicInteger (int initialValue): Creates a new AtomicInteger with a given initial value.
AddAddGet (int dalta): add the given value to the current value in atomic mode.
Get (): get the current value

Code example:
Only change the Bank class. The rest of the code is the same as the first example above.

 1 class Bank { 2         private AtomicInteger account = new AtomicInteger(100); 3  4         public AtomicInteger getAccount() { 5             return account; 6         } 7  8         public void save(int money) { 9             account.addAndGet(money);10         }11     } 

Supplement-atomic operations mainly include:
Read and Write operations for referenced variables and most original variables (except long and double;
Read and Write operations on all variables (including long and double) modified with volatile.


How many java multithreading implementation methods are available? What are the implementation methods of synchronization?

Multithreading can be implemented in two ways: Inheriting the Thread class and implementing the Runnable interface.
There are two types of synchronization implementation: synchronized, wait, and Y.

Java Thread Synchronization Method

Wait for wake-up Mechanism
Wait (): Let the thread wait. Stores threads in a thread pool.
Running y (): Wake up the waiting thread. Usually wake up the first thread in the thread pool. Temporarily blocks the wake-up thread.
Yyall (): wake up all the waiting threads. Wake up all threads in the thread pool and turn them from the frozen body to the temporary blocking status.
These three methods are used to operate the thread, but are defined in the Object class. Why?
These three methods need to be defined in synchronization when used, and the thread operated by these methods must be clear.
To put it simply. In the thread where A lock is wait, it can only be awakened by the notify method of A lock.
Therefore, the Lock Object of the wait notify method must be indicated, and the lock object can be any object.
Methods that can be called by any Object must be defined in the Object class.
Note: The wait for wake-up mechanism is usually used in synchronization because the lock is required.
In addition, you must specify the Lock Object for wait notify.

The lock after JDK1.5

After jdk1.5,
Some new features have emerged, and the principle thread has been improved.
An interface Lock is provided in the java. util. concurrent. locks package. Synchronized is replaced.
Synchronized. The lock operation is implicit.
The Lock operation is displayed.
There are two methods to accomplish this:
Lock (): Get the lock.
Unlock (): Release the lock.
There is also an object, Condition.
The appearance of this Object replaces the methods of the wait monitoring y policyall operations monitor in the Object.
Alternative method: await signal signalAll.

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.