Synchronized and wait, notify

Source: Internet
Author: User

Methods control access to class member variables: each class instance corresponds to a lock, and each synchronized method must obtain the lock of the class instance that calls this method before execution. Otherwise, the corresponding thread is blocked, once the method is executed, the lock is exclusive until the lock is released when the method is returned. Then, the blocked thread can obtain the lock and re-enter the executable status.

Wait ()/notify (): calls the wait () method of any object to cause thread blocking and the lock on this object is released. However, calling the notify () method of any object causes the wait () method of the object to be called () method ).

Relationship between synchronized and wait () and notify:

1. Where synchronized exists, wait and notify may not be available.

2. with wait, synchronized must be used in zooy. this is because wait and notify are not thread classes, but methods that every object has. Moreover, these two methods are related to the object lock. Where there is a lock, there must be synchronized.

In addition, note that if you want to use the notify and wait methods together, you must first call notify and then call wait, this thread is no longer the current thread.

Note: It is best to use the while clause before calling the wait () method, instead of the if clause. The while clause can be used to determine conditions again after being wakeup, while the if clause can only be judged once;

Four States of a thread

1. New status: the thread has been created but not executed (start () has not been called ).

2. executable status: the thread can be executed, although not necessarily in progress. The CPU time may be allocated to this thread at any time for execution.

3. Death state: Normally, running () returns to cause the thread to die. Calling stop () or destroy () has the same effect, but is not recommended. The former produces exceptions, and the latter produces exceptions.

Is forced to terminate, will not release the lock.

4. Blocking status: the thread will not be allocated CPU time and cannot be executed.

First of all, all the methods described above belong to the Thread class, but this pair (wait ()/notify () is directly affiliated to the Object class, that is, all objects have this

Method. It seems incredible at the beginning, but it is actually quite natural, because this pair of methods will release the occupied lock when blocking, and the lock is owned by any object and calls any

The wait () method of the object causes thread blocking and the lock on the object is released.

However, calling the notify () method of any object causes a randomly selected unblocking in the thread that is blocked by calling the wait () method of the object (but it will not be true until the lock is obtained ).

Executable ).

Secondly, all the methods described above can be called anywhere, but this pair of methods must be called in the synchronized method or block for a very simple reason.

Only when the current thread in the synchronized method or block occupies the lock can the lock be released.

In the same way, the lock on the object that calls this method must be owned by the current thread so that the lock can be released. Therefore, this pair of method calls must be placed in

In the synchronized method or block, the lock object of this method or block is the object that calls this pair of methods. If this condition is not met, the program can still be compiled,

IllegalMonitorStateException exception.

The preceding features of the wait () and notify () methods determine that they are often used together with the synchronized method or block to compare them with the inter-process communication machine of the operating system.

Synchronized methods or blocks provide features similar to operating system primitives, and their execution will not be affected by the multi-thread mechanism.

It is equivalent to the block and wakeup primitives (both of these methods are declared as synchronized ).

The combination of these algorithms allows us to implement a series of exquisite inter-process communication algorithms (such as semaphore algorithms) on the operating system and solve various complicated inter-thread communication problems. About

The wait () and notify () methods are further described as follows:

First, the thread that calls the notify () method to lift the blocking is randomly selected from the thread that is blocked by calling the wait () method of the object. We cannot predict which thread

Will be selected, so be especially careful when programming to avoid problems caused by this uncertainty.

Second: In addition to notify (), there is also a method notifyAll () that can also play a similar role. The only difference is that calling the notifyAll () method will call

All the threads blocked by the wait () method are all blocked at one time. Of course, only the thread that gets the lock can enter the executable state.

When talking about blocking, we can't help but talk about deadlocks. A brief analysis shows that calls of the suspend () method and the wait () method without specifying the timeout period may lead to deadlocks. Sorry

Yes, Java does not support avoiding deadlocks at the language level. We must be careful when programming to avoid deadlocks.

We have analyzed various methods for implementing thread blocking in Java. We have focused on the wait () and notify () methods, because they are the most powerful and use

Most flexible, but this also leads to low efficiency and error-prone. In actual use, we should use various methods flexibly to better achieve our goal.

VII. daemon thread

A daemon is a special type of thread. It differs from a common thread because it is not the core part of an application. When all the non-daemon threads of an application terminate, that is

If there is still a daemon thread running, the application will be terminated. Otherwise, the application will not be terminated as long as there is a non-daemon thread running. The daemon thread is generally used

It provides services by threads.

You can call the isDaemon () method to determine whether a thread is a daemon thread, or call the setDaemon () method to set a thread as a daemon thread.

After modifying the method with the synchronized keyword, the program will judge whether the method can be called Based on the lock of the object that calls this method.

 

For the instance method of a class, when this method is called by a thread, other threads can no longer call this method through the same object (this method can be called through another object of this class ).

 

For a static method of a class, when a thread calls this method through a class object, other threads cannot call this method through the class object. Because only one class object is created by a virtual machine during class loading, this method can only be called by one thread at the same time.

 

In servlet programs, containers only instantiate one servlet object. Multiple users access the same servlet object. Therefore, the servlet method is synchronously modified, this prevents multiple users from calling a method at the same time to avoid sharing conflicts.

 

When creating a multi-threaded program, when calling the instance method of a class through an object in the Child thread, this object should be created in the main thread, the object reference is passed into the sub-thread through the sub-thread constructor or other interface methods for use by the sub-thread.

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.