Java Threads (2)--Sync and lock

Source: Internet
Author: User

Reference reprint: http://rainyear.iteye.com/blog/1734311

http://turandot.iteye.com/blog/1704027

Http://www.cnblogs.com/fguozhu/articles/2657904.html

http://lavasoft.blog.51cto.com/62575/99155

1. Thread's memory model

Java as a platform-independent language, JLS (Java language Specification) defines a unified memory management model JMM(Java memory model), JMM masking the underlying platform memory management details, in a multithreaded environment must solve the problem of visibility and order. The JMM specifies that the JVM has main memory and working memory (working memory), all class instances, static data, and so on, which are shared by multiple threads. While working memory is the variable that the thread copies from the main memory and the local variables obtained by the access method, the other threads that are private to each thread are inaccessible, and each thread operates on the variable by copying it from main memory to working memory and then manipulating it. Data communication between multiple threads cannot be communicated directly to each other, only through shared variables.

Important pictures to look at three times, from the three memory model of the article excerpt from the image meaning is consistent. That

1. All threads share main memory

2. Each thread has its own working memory

Note that first you need to understand what is main memory, the main memory is what we call memory. So what are the variables that are shared? The class variable (static variable), the instance variable (member variable) is shared, is not safe. Local variables are not shared and local variables are safe, as variables in the method body are unshared.

Why are threads unsafe? From the introduction above, we can see that each thread takes data from the main memory, changes the data and puts it back into main memory. When multiple threads change the variables in main memory, the value of this variable is not determined. To be exact, thread 1 only wants the variable a plus 1, and the second time out a is not what you want. That's not safe!

2. What is multithreading

The previous section has learned about threads, which are multiple threads running. It seems to explain very funny, but I think multithreading is not so complicated, do not think that security issues on the head, multithreading is not necessarily thread insecure. As mentioned above, there is a thread-safety problem with multiple threads sharing the same variable, and on the contrary, there is no problem in the case of shared variables. I once tested multithreading no problem, later found that I did not share variables in the test, the body of each thread is a new object, so there is no security issue. However, the usual use of more is shared. That is, the parameters of multiple threads are the same instance.

3. Sync Lock 3.1 What is locked

Want to sync must be locked, only locked, others can not access the things I use, I released the lock can be used by others, so that I use the scope of the absolute control of variables, that is, thread safety, that is, synchronization. So what is a lock?

Each object in Java has a built-in lock . When the program runs to a non-static synchronized synchronization method, the lock associated with the current instance (this instance) of the executing code class is automatically obtained. Acquiring a lock on an object is also known as acquiring a lock, locking an object, locking on an object, or synchronizing on an object.

An object has only one lock . Therefore, if a thread obtains the lock, no other thread can get the lock until the first thread releases (or returns) the lock. This also means that no other thread can enter the synchronized method or block of code on the object until the lock is freed.

Read the introduction, Understand:

    • The object has a lock, obtained through synchronize;
    • Object has only one lock;
    • The Synchronize code block cannot be accessed by other threads after the object is locked;
    • The lock is for the object;
    • This indicates the current object
3.2 Method Lock

The following is an easy to understand and see example, is the method header plus keyword synchronized

     Public synchronized void setName (String name) {        this. Name = name;    } 
3.3 Objects Locked

Object Lockout This,this represents the current object.

 Public synchronized int GetX () {        return x + +;    } With     public int  GetX () {        synchronized (this) {             return x;        }    } The effect is exactly the same. 
3.4 Static method Lockout
To synchronize a static method, you need a lock for the entire class object, which is the Class (XXX). class ). For example:publicstaticsynchronizedint  setName (String name)      {=  Name;} Equivalent to publicstaticint  setName (String name) {      synchronized (Xxx.class) {            = name;      }}
3.5 What happens if a thread doesn't get a lock?
If a thread attempts to enter the synchronization method and its lock is already occupied, the thread is blocked on the object. Essentially, a thread enters a pool of that object, where it must wait until its lock is freed and the thread becomes operational or running again. When considering blocking, it is important to note which object is being used for locking: 1. Threads that call non-static synchronization methods on the same object will block each other. if it is a different object, each thread has its own lock on the object, and the threads do not interfere with each other. 2. Threads that call static synchronization methods in the same class will block each other, and they are all locked on identical class objects. 3. Static synchronization methods and non-static synchronization methods will never block each other, because static methods are locked on the class object, and non-static methods are locked on the object of the class. 4, for the synchronization of the code block, to see what the object has been used to lock (synchronized the contents of the parentheses behind). Threads that synchronize on the same object block each other, and threads that are locked on different objects will never block each other .

See Introduction Understand: Lock must be the object of locks.

3.6 Dead Lock

Dead locks, very familiar names. Deadlocks are threads waiting for each other, a requires B resources, but B's resources are not released by B, a blocking wait, B requires a resource, but a's resources are not released by a hold, b blocking wait. Is I wait for you, you wait for me, the cycle of death. Instance:

 PackageCom.test.java.thread;/*** Deadlock * Created by MRF on 2016/2/26.*/ Public classDeadlockrisk {Private Static classResource { Public intvalue; }    PrivateResource Resourcea =NewResource (); PrivateResource RESOURCEB =NewResource ();  Public intRead () {synchronized(resourcea) {synchronized(RESOURCEB) {System.out.println ("Read"); returnResourceb.value +Resourcea.value; }        }    }     Public voidWriteintAintb) {synchronized(RESOURCEB) {synchronized(resourcea) {System.out.println ("Write"); Resourcea.value=A; Resourceb.value=b; }        }    }}classDeadlockrunImplementsrunnable{deadlockrisk Deadlockrisk=NewDeadlockrisk (); @Override Public voidrun () {Deadlockrisk.write (The);    Deadlockrisk.read (); }     Public Static voidMain (string[] args) {Deadlockrun Deadlockrun=NewDeadlockrun (); Thread T1=NewThread (Deadlockrun); Thread T2=NewThread (Deadlockrun);        T1.start ();    T2.start (); }}
View Code

In this example, notice that the two-thread declaration process is for the same object, so there is a resource scramble behavior.

4 Summary
1, the purpose of thread synchronization is to protect multiple threads to ask a resource when the destruction of resources. 2, thread synchronization method is implemented by the lock, each object has a cut only a lock, the lock with a specific object, the thread once the object lock, the other access to the object's thread can no longer access the object's other synchronization methods. 3, for the static synchronization method, the lock is for this class, the lock object is the class object. Static and non-static methods of locking do not interfere. A thread acquires the lock, which is obtained when a synchronization method on another object is accessed in a synchronous method. 4, for synchronization, to be awake at all times on which object synchronization, this is the key. 5, write thread-safe classes, you need to pay attention to multiple threads competing access to the logic and security of the resources to make the right judgment, the "atomic" operation to make an analysis, and ensure that other threads during atomic operation can not access the competing resources. 6. When multiple threads wait for an object lock, the thread that does not acquire the lock will block. 7, deadlock is between the threads waiting for lock-lock caused by, in practice, the probability of occurring is very small. Really let you write a deadlock program, not necessarily good, hehe. However, once the program has a deadlock, the program will die.

Also, synchronization is achieved by locking, that is, atomic operations do not affect each other; Locks are objects, class objects, or instance objects.

Java Threads (2)--Sync and lock

Related Article

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.