Understanding of JAVA multi-thread concurrent programming and java multi-thread concurrent programming

Source: Internet
Author: User

Understanding of JAVA multi-thread concurrent programming and java multi-thread concurrent programming

Understanding of JAVA multi-thread concurrent programming

Java multi-thread programming focuses on concurrent access to a single resource. This article analyzes the understanding of concurrent programming from the perspective of how Java supports concurrent access, it is also a summary of what I learned some time ago.

Thread status conversion

The Java language defines the thread state in step 5. at any point in time, a thread can only have one and only one of the states. The States in these five are:

New: the thread that has not been started after creation is in this status.

Ø Runable: Runable includes Running and Ready in the operating system thread state, that is, the thread in this state may be executing, or may be waiting for the CPU to allocate the execution time for it.

Long wait (Waiting): threads in this status will not be allocated CPU execution time, they will wait for the explicit wake-up by other threads. The following method causes the thread to wait for an indefinite period:

U does not have the Object. wait () method for setting the Timeout parameter.

U does not have the Thread. join () method for setting the Timeout parameter.

U LockSupport. park () method.

Ø TimedWaiting: threads in this status will not be allocated CPU execution time, but do not need to wait for other threads to explicitly wake up. After a certain period of time, they will be automatically awakened by the system. The following method causes the thread to wait for a time limit:

Thread. sleep () method.

U sets the Object. wait () method with the Timeout parameter.

U sets the Thread. join () method of the Timeout parameter.

U LockSupport. parkNanos () method

U LockSupport. parkUntil () method

Ø Blocked: The thread is Blocked. The difference between the blocking status and the waiting status is: the blocking status gets an exclusive lock while waiting, this event will occur when another thread waives the lock: while the "Wait state" is waiting for a period of time, or both wake up the action. The thread enters this state when the program waits to enter the synchronization area.

Ø Terminated: the State of the thread in which the thread has been Terminated.

Various status changes such:


Resource Monitor

When performing multi-threaded concurrent operations, the key task is how to ensure secure access to competing resources in multiple concurrent threads. Secure access means that when a thread is in a competitive resource operation (modifying the resource status, other threads cannot operate on this competitive resource (if all threads perform read operations on this resource, no security issues will occur ).

Java puts forward the concept of monitor to solve such problems. In the image, a Resource Monitor includes a security protection shell on the resource to be accessed, such:


The Java Virtual Machine ensures that at the same time point, only one thread can obtain the resource's monitor. In other words, the lock is obtained for the resource. The thread that acquires the lock can perform subsequent operations. The thread that does not obtain the lock can only wait or block.

A thread that has obtained the resource's monitor. It can also obtain the monitor multiple times later. Each time it gets the monitor, the lock count will be increased by 1, and the resource monitor will be exited every time, the lock count is also reduced by 1. When the thread completely exits the Resource Monitor, the lock count is also cleared. In this case, other threads can obtain the monitor of the resource.

Java monitor supports two threads, mutual exclusion and collaboration. The Java virtual machine uses Object locks to achieve mutual exclusion. Multiple Threads can work independently on the same shared data without interfering with each other. Collaboration is achieved through the wait and notify methods of the Object class, allowing multiple threads to work together for the same goal.

Mutex can be used to execute a piece of code called the monitoring area in multiple threads. During a task, only one thread executes the monitoring area on a specific monitor. Generally, mutex is important only when multiple threads need to share data or other resources. If the two threads do not use the public data or resources of the task, they usually do not interfere with each other, no mutex execution is required.

The mutually exclusive help thread is not disturbed by other threads when accessing shared data, while the cooperative help thread works with other threads.

Collaboration is important when a thread needs data in a special State and another thread is responsible for changing the state of the data. This is an example for producers and consumers. A "read thread" reads data from the data buffer, while another "Write thread" writes data to the data buffer. Data can be read only when the read thread buffer is in the "not empty" status. If the read thread finds that the data buffer is empty, it must wait.

Java provides the "wait and wake up" method to support multi-threaded collaboration. The corresponding Java API is the wait (), Policy (), and policyall () Methods of the Object.

The wait () method makes the current thread have to wait until another thread calls y () orPolicyall() Method.

  The current thread must have the monitor of the current object, that is, lock.

The thread calls the wait () method, releases its ownership of the lock, and waits for another thread to notify it (the notification method is the Y () or yyall () method ), in this way, it can regain the ownership of the lock and resume execution.

Make sure that the wait () method has a lock. That is, the wait () method must be called in the synchronized method or synchronized block.

  A small comparison:

When the thread calls the wait () method, it releases the object lock.

Another method that causes Thread suspension: Thread. sleep (), which causes the Thread to sleep for a specified number of milliseconds, but the Thread will not release the object lock during sleep.

The notify () method will wake up a thread waiting for the lock of the current object.

If multiple threads are waiting, one of them will be awakened. This option is random and depends on the specific implementation. (The thread waits for the lock of an object because one of the wait methods is called ).

  The wake-up thread cannot be executed. You need to wait until the current thread abandons the Lock of this object.

The awakened thread will compete with other threads in the usual way to obtain the object lock. That is to say, the Awakened thread has no priority and no disadvantage. The next thread of the object still needs to compete through general competition.

  The notify () method should be called by the thread that owns the object lock.

(Thismethod shocould only be called by a thread that is the owner of this object 'smonitor .)

In other words, like the wait () method, the invoke y method call must be placed in the synchronized method or synchronized block.

As mentioned above, when the wait, nofity, and policyall methods are called, make sure that you have obtained this pair of monitors on the called object. That is, the thread operates on the lock of this object.

The owner of a lock that changes a thread into an object is through the following three methods:

1. Execute the synchronized instance method of this object.

2. Execute the synchronized statement block of this object. The block lock of this statement is the object.

3. Execute the synchronized and static methods of the Class Object.

 

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.