Java Multithreading (vi) Synchronized keywords
Multi-threaded synchronization mechanism to lock the resources, so that at the same time, only one thread can operate, synchronous to solve the problem that can occur when multiple threads concurrently access.
The synchronization mechanism can be implemented using the synchronized keyword .
When the Synchronized keyword modifies a method, the method is called a synchronous method .
When the Synchronized method finishes or an exception occurs, the lock is automatically released.
The following example is used to parse the usage of the Synchronized keyword.
1. Whether to use different synchronized keywordsExample Program 1
Public class ThreadTest
{
Public static void main (string[] args)
{
Example Example = new Example ();
Thread T1 = new Thread1 (example);
Thread t2 = new Thread1 (example);
T1.start ();
T2.start ();
}
}
class Example
{
Public synchronized void Execute ()
{
for (int i = 0; i < ten; ++i)
{
Try
{
Thread.Sleep (+);
}
Catch (Interruptedexception e)
{
E.printstacktrace ();
}
System. out. println ("Hello:" + i);
}
}
}
class Thread1 extends Thread
{
Private Example Example;
Public Thread1 (Example Example)
{
this. Example = example;
}
@Override
Public void run ()
{
Example.execute ();
}
}
If you add the synchronized keyword before the Execute () method, the execution result of this example program will be very different.
If you do not add the Synchronized keyword , two threads execute the Execute () method at the same time, and the output is two sets of concurrency .
If you add the Synchronized keyword , you will first output a set of 0 to 9 and then output the next set, which means that two threads are executed sequentially .
2. Multithreading scenarios for multiple methods
To change the program, add a Method Execute2 () to the example class.
Then write a thread class thread2,thread2 the Run () method executes the Execute2 (). The two methods in the example class are decorated with the synchronized keyword.
Example Program 2
Public classthreadtest{Public static voidMain (string[] args) {Example Example =NewExample (); Thread T1 =NewThread1 (example); Thread t2 =NewThread2 (example); T1.start (); T2.start (); }}classexample{Public synchronized voidExecute () { for(inti = 0; I < 20; ++i) {Try{Thread.Sleep (Long) Math.random () * 1000); }Catch(Interruptedexception e) {E.printstacktrace (); } System. out. println ("Hello:" + i); } }Public synchronized voidExecute2 () { for(inti = 0; I < 20; ++i) {Try{Thread.Sleep (Long) Math.random () * 1000); }Catch(Interruptedexception e) {E.printstacktrace (); } System. out. println ("World:" + i); } }}classThread1extends Thread{PrivateExample Example; PublicThread1 (Example Example) { This. Example = example; } @OverridePublic voidRun () {example.execute (); }}classThread2extends Thread{PrivateExample Example; PublicThread2 (Example Example) { This. Example = example; } @OverridePublic voidRun () {example.execute2 (); }}
If you remove the Synchronized keyword, the two methods are executed concurrently and do not affect each other.
However, even two methods are written in the example program:
The execution result is always executing the output of one thread and then executing another thread.
Description
If an object has multiple synchronized methods and a thread has entered a synchronized method at some point, the other thread is unable to access any of the synchronized methods of the object until the method has finished executing.
Conclusion :
When the synchronized keyword Modifies a method, the method is called a synchronous method .
Each object in Java has a lock , or monitor , that locks the object when a thread accesses the synchronized method of an object. No other thread can access the object's Synchronized method (this refers to all synchronous methods, not just the same method) until the previous thread executes the method (or throws an exception) before releasing the object's lock. Other threads will be able to access the object's synchronized method again.
Note that this is a lock on the object , and if it is a different object, there is no restriction between the objects.
When trying to construct a second thread object in code, passing in a new example object, there is no restriction between the execution of the two threads.
3. Consider a static synchronization method
When a synchronized keyword Modification method is also modified by static , the non-static synchronization method locks the object, but the static method does not belong to the object, but belongs to the class, which The C of the class where this method resides Lass The object is locked .
A class, regardless of how many objects are generated, corresponds to the same class object .
Example Program 3
Public classthreadtest{Public static voidMain (string[] args) {Example Example =NewExample (); Thread T1 =NewThread1 (example); Here, even if you pass in a different object,static method synchronization still does not allow multiple threads to execute concurrentlyExample =NewExample (); Thread t2 =NewThread2 (example); T1.start (); T2.start (); }}classexample{Public synchronized static voidExecute () { for(inti = 0; I < 20; ++i) {Try{Thread.Sleep (Long) Math.random () * 1000); }Catch(Interruptedexception e) {E.printstacktrace (); } System. out. println ("Hello:" + i); } }Public synchronized static voidExecute2 () { for(inti = 0; I < 20; ++i) {Try{Thread.Sleep (Long) Math.random () * 1000); }Catch(Interruptedexception e) {E.printstacktrace (); } System. out. println ("World:" + i); } }}classThread1extends Thread{PrivateExample Example; PublicThread1 (Example Example) { This. Example = example; } @OverridePublic voidRun () {example.execute (); }}classThread2extends Thread{PrivateExample Example; PublicThread2 (Example Example) { This. Example = example; } @OverridePublic voidRun () {example.execute2 (); }}
So if it's a static method (Execute () and Execute2 () plus the static keyword ), even if you pass in a different example object to two threads, the two threads are still Each other , the first one must be executed before the next.
Conclusion:
If a synchronized method is static, then when the thread accesses the method, it locks not the object that the Synchronized method resides in, but the class object that corresponds to the synchronized method. In Java, no matter how many objects a class has, these objects correspond to a unique class object, so when a thread accesses two static,synchronized methods of two objects of the same class individually, their order of execution is also sequential, that is, a thread first executes the method, Another thread does not start until after execution is complete.
4. Synchronized Block
Synchronized block notation:
Synchronized (object)
{
}
Indicates that the thread will lock object object when executing. (Note that this object can be an object of any class, or you can use the This keyword).
This allows you to set your own lock object.
Example Program 4
Public classthreadtest{Public static voidMain (string[] args) {Example Example =NewExample (); Thread T1 =NewThread1 (example); Thread t2 =NewThread2 (example); T1.start (); T2.start (); }}classexample{PrivateObject object =NewObject ();Public voidExecute () {synchronized(object) { for(inti = 0; I < 20; ++i) {Try{Thread.Sleep (Long) Math.random () * 1000); }Catch(Interruptedexception e) {E.printstacktrace (); } System. out. println ("Hello:" + i); } } }Public voidExecute2 () {synchronized(object) { for(inti = 0; I < 20; ++i) {Try{Thread.Sleep (Long) Math.random () * 1000); }Catch(Interruptedexception e) {E.printstacktrace (); } System. out. println ("World:" + i); } } }}classThread1extends Thread{PrivateExample Example; PublicThread1 (Example Example) { This. Example = example; } @OverridePublic voidRun () {example.execute (); }}classThread2extends Thread{PrivateExample Example; PublicThread2 (Example Example) { This. Example = example; } @OverridePublic voidRun () {example.execute2 (); }}
Example program 4 achieves the same effect as the example program 2, is to make the execution order of two threads, not concurrency, when one thread executes, the object is locked, the other thread cannot execute the corresponding block.
The Synchronized method is actually equivalent to wrapping all the statements in the method with a synchronized block, and then passing in the This keyword in parentheses in the synchronized block. Of course, if it is a static method, it is a class object that needs to be locked.
Perhaps only a few lines of code in a method will involve thread synchronization problems, so the synchronized block is more granular than the Synchronized method to control access to multiple threads, and only the contents of the synchronized block cannot be accessed by multiple threads at the same time. The other statements in the method can still be accessed by multiple threads at the same time (both before and after the synchronized block).
Note: Data that is protected by synchronized should be private .
Conclusion:
The synchronized method is a coarse-grained concurrency control where only one thread can execute the synchronized method at a time;
The synchronized block is a fine-grained concurrency control that synchronizes code in the block only, and other code that is inside the method and outside the synchronized block can be accessed concurrently by multiple threads.
Concurrent Packages for JDK 5.0
Resolving thread synchronization problems with the Synchronized keyword can lead to some execution efficiency problems.
These problems cannot be avoided by JDK1.4 and before.
JDK 5.0 introduces such a package: Java.util.concurrent:
Http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/package-frame.html
Specifically address this issue.
Confined to space, no longer described here.
Resources
Santhiya Garden Zhang Long teacher Java SE Series video tutorial.
Source: http://www.cnblogs.com/mengdd/archive/2013/02/16/2913806.html
Java Multithreading (vi) Synchronized keyword description