Synchronization method method for sleep and wait thread synchronization

Source: Internet
Author: User
Tags tools and utilities java util

When a thread enters one of the object's synchronized methods, does the other thread have access to other methods of this object?

In two different cases

1): Non-synchronous method to enter this object

Answer: Yes

2): Synchronization method to enter this object

Answer: No, yes.

Sleep refers to when the thread is called, the CPU does not work, the image is described as "occupy the CPU Sleep", at this time, the system's CPU part of the resources are occupied, other threads can not enter, will increase the time limit.
Wait means that the thread is in the waiting state and is visually described as "waiting for CPU", at which point the thread does not occupy any resources and does not increase the time limit.
So
Sleep (100L) means: Consumes CPU, thread sleeps 100 milliseconds
Wait (100L) means: CPU not occupied, thread waits 100 milliseconds
Summary of Methods (7) for thread synchronization in Java

Methods of synchronization:

First, the synchronization method is a method of synchronized keyword modification. Because each object in Java has a built-in lock, the built-in lock protects the entire method when the method is decorated with this keyword. You need to get the built-in lock before calling the method, otherwise it will be in a blocking state. Note: The Synchronized keyword can also modify a static method, at which point the entire class is locked if the static method is called.

second, synchronous code blockThat is, a statement block that has the synchronized keyword modifier. The block of statements decorated with this keyword is automatically added with the built-in lock, which enables synchronization of code such as:
Synchronized (object) {}
Note: Synchronization is a high-overhead operation, so you should minimize the content of synchronization. It is usually not necessary to synchronize the entire method, using the synchronized code block to synchronize the key code.
    Package com.xhj.thread;     /**     * Application of thread synchronization     *      * @author Xiehejun * * */Public    class Synchronizedthread {         class Bank {            private int account = +;            public int Getaccount () {                return account;            }             /**             * Implemented with synchronous method             *              * @param money             *            /public synchronized void Save (Int. money) {Account                + = Money;            }             /** *             implemented with synchronous code blocks * * @param money */public            void save1 (int. money) {                synchronized (this) { C28/>account + = Money;}}        
third, wait and notify

Wait (): causes a thread to be in a wait state and releases the lock of the object it holds.

Sleep (): Makes a running thread sleep, is a static method that calls this method to catch the interruptedexception exception.
Notify (): Wakes up a waiting thread, noting that when this method is called, it does not actually wake up a waiting state thread, but is determined by the JVM to wake up which thread, and not by priority.
Allnotity (): Wakes all the threads that are in the waiting state, noting that they do not give all the wake-up threads an object lock, but instead let them compete.

Iv. using special domain variables (volatile) for thread synchronization
The A.volatile keyword provides a lock-free mechanism for accessing domain variables
B. Using a volatile modifier domain is equivalent to telling a virtual machine that the domain might be updated by another thread
C. Therefore, each time the domain is used, it is recalculated instead of using the value in the Register
D.volatile does not provide any atomic manipulation, nor can it be used to modify a final type of variable
For example:
In the example above, thread synchronization can be achieved simply by adding a volatile modifier to the account.
code example:
        Just give the code to be modified, the rest of the code with the same        class Bank {            //the variable that needs to be synchronized plus the volatile            private volatile int account = +;             public int Getaccount () {                return account;            }            There is no longer a need for synchronized public             void Save (int money) {Account                + = money;            }        }
V. Using a re-entry lock for thread synchronization
A java.util.concurrent package has been added to support synchronization in JavaSE5.0.
The Reentrantlock class is a re-entrant, mutex, and lock interface that implements the same basic behavior and semantics as using the Synchronized method, and extends its capabilities.
Common methods of the Reenreantlock class are:
Note: Reentrantlock () also has a construction method that can create a fair lock, but is not recommended because it can significantly reduce the efficiency of program operation
For example:
On the basis of the above example, the rewritten code is:
       Just give the code to be modified, the rest of the code with the same        class Bank {                        private int account = +;            Need to declare this lock            private lock lock = new Reentrantlock ();            public int Getaccount () {                return account;            }            Synchronized public             void Save (int money) {                lock.lock () is no longer required here;                try{account                    + = money;                } finally{                    Lock.unlock ();                }                            }        }
Note: About the lock object and synchronized keyword selection:
A. It is best to use a mechanism provided by the Java.util.concurrent package to help users handle all lock-related code.
B. If the synchronized keyword satisfies the user's needs, use synchronized because it simplifies the code
C. If you need more advanced features, use the Reentrantlock class, you should pay attention to release the lock in time, otherwise there will be deadlock, usually in the finally code release lock

7. Using atomic variables for thread synchronization

The root cause of the need to use thread synchronization is that operations on ordinary variables are not atomic.

So what is atomic manipulation? Atomic manipulation means reading the value of a variable, modifying the value of a variable, saving the value of a variable as a whole--these behaviors are either completed at the same time or are not completed. A tool class that creates an atomic type variable is provided in the Java util.concurrent.atomic package to simplify thread synchronization. Where the atomicinteger table can atomically update the value of int, available in an application (such as an atom-incremented counter), but cannot be used to replace an integer; Allows for unified access to tools and utilities that deal with the opportunity number class.

Common methods of the Atomicinteger class:

Atomicinteger (int initialvalue): Creates a new with the given initial value

Atomicintegeraddaddget (int dalta): atomically adds the given value to the current value

Get (): Gets the current value

code example:

Just change the bank class, the rest of the code is the same as the first example above

Class Bank {    private Atomicinteger account = new Atomicinteger (+);    Public Atomicinteger Getaccount () {        return account;     }     public void Save (int money) {        account.addandget (money);    }}

Synchronization method method for sleep and wait thread synchronization

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.