Java multithreaded design mode (1)

Source: Internet
Author: User
Tags instance method

1 threads in several ways to explain

Thread.Sleep (long milliseconds)

Sleeps the current thread for a specified amount of time, gives control to another thread, and the dormant thread still owns the lock it occupies.

Thread.yield ();

Pauses or discards the currently executing thread and executes other threads, but does not release the locks owned by the thread, and the thread discards, allowing other identical or higher threads to run.

T.join ()

Wait for the t thread in a thread, you can specify a certain amount of time to continue execution or wait indefinitely

T.interrupt ()

The thread that interrupts T, can wake up The thread that is in the sleep,join and wait states,

P.wait ()

A thread can wait for an object it locks on, and when it waits, it releases the lock on the object and pauses into hibernation, and it keeps resting until the time expires, the thread is interrupted, and the object is notified. It is not executed until it has been notified by other threads, such as when the object calls notify () and Notifyall ().

For the use of wait and notify and Notifyall with a synchronous code block or synchronous method to obtain the lock of the object, after using wait, the object will first get the lock, and then into the object's wait set, pause the current thread, release the lock of the object, Wait set on the object waits for the

For direct wait () is this.wait (), the thread that executes wait () waits in the wait set of this.

Yield and sleep differences

The Sleep method causes the currently running thread to be asleep for a period of time, entering the non-operational state, which is set by the program, and it can only be woken up or slept until it continues to run;

The yield method causes the current thread to give up the CPU possession, which is the time slice and re-queue, but the time is not set and the thread is still operational

The yield () method corresponds to the following actions: first detect whether the current priority of the thread is in the same operational state, if so, the CPU's possession to the thread, otherwise continue to run the original thread, so the yield () method is called "concession", it will run the opportunity to the same level of other threads.

The Sleep method allows a lower-priority thread to get a run opportunity, but when the yield () method executes, the current thread is still in a running state, it waits for a CPU call in the queue, so it is operational (note that it is not running), so it is not possible to let the lower-priority thread get CPU possession at this time. In a running system, if a higher-priority thread does not call the sleep method and is not blocked by I/O, the lower-priority thread can only wait for all higher-priority threads to run to the end before the opportunity runs.

Yield () simply brings the current thread back to the operational state, and all threads that execute yield () are likely to be executed immediately after entering the operational state, so the yield () method only gives the same priority thread an opportunity to execute
2 Thread Start-up

The start of a thread is always called by the start () method, and the Thread.Start () method starts the thread so that it enters a ready state, when the CPU allocates time slices to the thread, the run () method is executed by the JVM, and the reason for the start and run method is because the JVM To create a separate thread that differs from the normal method call, starting a thread is done by the Start method, and start is implemented by the local method and needs to be called in the display. The Run method is the part of the task that is actually executed, and the other advantage is that when an object needs to inherit multiple classes, it is possible to implement the Runnable interface for the specific task, and then pass it to thread to avoid the multiple inheritance problem of Java inherited by the thread class.

For an instance variable of the same thread class, you can call the Start method only once, and once the Start method is called, it will become the end start state, and when it calls the Start method again, it will appear illegalthreadstateexception, It will be backed up so that the thread's start will not be executed again. The start method of the thread class uses the balking pattern.

Multithreading is done for multiple threads operating under the same object.


3 Single Threaded execution Pattern

Single threaded execution means "allow only one thread to execute", which indicates that only one thread must be allowed to execute when invoking this method or object. Use synchronized to set the listener for the object in the Synchronized method body or in the synchronization block. It is important to note that the synchronized instance method shares the lock of the class's instance object, while the synchronized class method, the static synchronized method, shares the lock of the class, which is completely different.

For one method of an object, when more than one thread needs access, these threads share all of the member properties of the object. A thread is the memory that shares this object.

Single threaded execution, as a class of shared resources, can be accessed by multiple threads. There are two methods, security methods and non-security methods, so-called security methods that are called by multiple threads without problems. A non-secure method may cause problems during multiple thread access. Non-secure methods need to be handled.
Applicability: When an instance of a shared resource class may be accessed by more than one thread, the state of the instance is modified, and in multiple threads, it is necessary to use synchronized to protect and implement critical intervals to monitor multi-threaded access when the state of the instance changes as a critical area.


4 Immutable Pattern

Immutable pattern refers to the "class with the ability to guarantee that the state of the instance will never change," again stating that the state of the instance refers to the member property of the class. The so-called cannot be changed, that is, the state of the class is only allowed to be assigned once, and does not provide any setter method to the outside world, and the property is private final, generally by the constructor for these states to assign values, of course, you can also declare the class as final. In this way, we can overcome the wasted time caused by using the shared mutex mechanism.

The immutable pattern participant is a class that cannot change the value of a field, and there is no way to change the value of a field. Once an instance of a immutable participant is created, the state is fixed and cannot be changed.
Applicability: When an instance is created, the state no longer changes. instances require multiple threads to be shared and accessed very frequently.


5 guarded suspension pattern--wait till I'm ready to call you again.

guarded suspension means "in multi-threading, when a thread accesses a resource and it is not appropriate to perform an operation immediately, the thread that wants to perform the operation must wait." "Guarded" is "protected" and suspension means "pause".

Guarded suspension requires the thread to wait. Wait is used, and all waiting threads are notified by Notifyall. The conditions that must be met for a thread to perform an operation are called alert conditions. Each thread in the execution, if not meet the alert conditions must be waiting, only after receiving the notification, to determine the success of the alert condition, can then proceed to perform the intended purpose operation.

The commonly used alert conditions are structured as follows:

Public synchronized void MethodName ()

{

While (negation of the warning condition)

Use wait;//here directly in the shared class wait, all the waiting will go into this wait set of the class instance waiting for

Jump out of the loop to show that the alert condition is met

Perform the purpose operation.

}
Note: You cannot replace a while with if, because whenever a thread in wait is awakened, it must be preceded by a warning condition before performing the purpose operation. The exception that catches wait must be included in the while loop body, otherwise the intent operation can be performed if an exception occurs. The wait here cannot be changed to sleep because the thread will always have the lock it has acquired by using sleep.

Here, wait and notify are hidden in shared resources so that the threads that use the shared resource do not need to consider these issues.

Guardedobject Participant is a defensive method Guardedmethod, generally is to use synchronized to decorate, when the thread executes this method, as long as the condition of the implementation of the alert will be executed, otherwise it will wait. Alert conditions change as the state of the instance changes. You also need a method statechangingmethod that changes the state of the instance to notify those waiting threads.

Generally use the while statement and the wait method to implement Guardedmethod, using notify and Notifyall to implement Statechangingmethod


6 balking Pattern

Balking pattern refers to the "multi-threaded access to shared resources, when it is not suitable for this operation, or there is no need for this operation, this time will be directly discarded to do this operation and return".

Balking pattern is also required for warning conditions. Guardedobject participants are a defensive approach Guardedmethod, generally using synchronized to decorate, when the thread executes this method, as long as the security conditions are met, or else. The Guard bar returns immediately and exits the method directly. The establishment of the alert condition will change as the state of the instance changes. You also need a method statechangingmethod that changes the state of the instance to notify those waiting threads.

Structure of the alert condition:

Public synchronized void Guardedmethod ()

{

if (warning condition negation)

return;

The condition of the alert is satisfied

Purpose operation

}
Applicability: When the online access warning condition is not established, do not need to deliberately execute the waiting time, do not want to wait until the establishment of the alert conditions, or the warning conditions only the first time. Note that the start method of a thread is used in this way, that is, only the first time it is set up, the second call will go wrong.

Java multithreaded design mode (1)

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.