Several important concepts of Java Multithreading

Source: Internet
Author: User
Several important concepts of Java Multithreading     Example of Java Multithreading

We can see that all the threads are running in the JVM and share a primary memory (global memory in the figure) with their own working memory (local variables in the figure ). It is important to understand the basic memory model of Java. Java thread Lifecycle
1. New: the thread object has been created, but the start () method has not been started. Therefore, it cannot be run.
2. runnable: After the start () method is called, the thread is in this State. Note that the thread is not in the running state after start. It enters the running state only when scheduler assigns CPU time to it.
3. Running: If the CPU schedules this thread, it is in the running state.
4. Blocked: When a thread in the running state is triggered by sleep (), wait (), or other reasons, it enters the blocked state. In this case, it can be awakened by scheduler y () to schedable scheduling such as runnable. Otherwise, it will stop at nothing.
5. dea d: When run () ends normally or is forced to end, the thread enters the dead state. In this case, the thread object handle may exist, and the START () method can also be called, but it does not work. To restart the thread, you must restart new. Atomic operation and volatile keywords
 An atomic operation is an operation that is not interrupted by the thread scheduling mechanism and cannot be divided. In Java, atomic operations on a variable include:
Use: transfers the context of the copy variable in the thread's working memory to the thread's execution engine. This operation occurs only when the thread executes a VM command using the variable value.
Assign: transfers the value in the thread execution engine to the copy variable in the thread working memory. This operation occurs only when the thread executes a VM command that assigns a value to the variable.
Read: (executed on the main memory) Transfer the variable context in the main memory to the thread working memory for subsequent load operations.
Load: (executed in the working memory) transfers the value of the variable after the read operation is performed in the main memory to the copy variable in the working memory of the thread.
Store: (executed in the working memory) transfers the context of the copy variable in the working memory to the main memory for subsequent write operations.
Write: (executed in the main memory) transfers the value of the variable after the store operation is performed in the thread working memory to the main variable in the main memory.
Lock: (executed when the thread needs to be closely synchronized with the main memory) will cause the thread to obtain a request permission (similar to the count) in a special lock ).
Unlock: (executed when the thread needs to be closely synchronized with the main memory) will cause the thread to release a request permission in a specific lock. The volatile modifier is used to declare that the access to a variable should be carried out in the primary memory, rather than being copied to the working memory. In this way, the load, store, read, and write operations on volatile variables of the basic type are atomic operations, even if the variable type is double or long. This operation is thread-safe, and does not require the Synchronized Locking Mechanism. However, if there are other code in addition to these operations, it is not an atomic operation and thread security cannot be ensured. For example, incremental or descending operations (++, --) cannot use the volatile variable to ensure thread security, because these operations actually include load-> change-> store3 operations. Before JVM 1.2, the actual implementation of the Java memory model determines that variables are always accessed from the primary memory, so that volatile can be ignored for those versions. However, with the evolution of Java, including the current j2se 5.0, the implementation of virtual machines has become more complex and new memory models and optimizations have been introduced, which is also a trend in the future. Under the new virtual machine model implementation, developers cannot assume that the variables are directly accessed from the main memory. If you want the "atomic operation" of a variable to meet the thread security requirements, the safest way is to declare the variable as vola tile. What is the role of volatile on arrays? The answer is that only the array reference itself is volatile, and the array elements will still be stored in the local memory. Currently, there is no way to specify the array element as volatile. Therefore, if multiple threads access an array element, you must use synchronized to protect data. Lock and synchronized keywords
To synchronize multiple threads, the Java language uses the Monitor (monitors), an advanced mechanism that limits only one thread to execute a piece of Monitor-protected code at a certain time point. The behaviors of the monitor are implemented through locks. Each object has a lock.
Each thread has a working memory, which stores the variables copied from the main memory shared by all threads. To access a shared variable, a thread usually needs to obtain a lock and refresh its working memory, which copies the shared value from the main memory to the working memory. When the thread is unlocked, the value in the working memory is written back to the main memory.
& N bsp; a thread can obtain the object lock multiple times. That is to say, one synchronized method calls another synchronized method, and the latter calls another Synchronized Method, and so on. JVM tracks the number of times an object is locked. If the object is not locked, its counter should be zero. When the thread gets the object lock for the first time, the counter is one. Every time the thread gets an object lock, the counter will add one. Of course, only threads that obtain the object lock for the first time can obtain the lock multiple times. Every time a thread exits a synchronized method, the counter is reduced by one. When it is reduced to zero, the object is unlocked, and other threads can use this object.
In addition, each class also has a lock (which belongs to the Class Object of the class), so that when the synchronized static method of the class reads static data, it will not interfere with each other.
Threads do not directly interact with each other. They only communicate with each other through the main memory. Since j2se 1.5, Java has the lock interface, which makes the lock concept clearer and easier to control thread synchronization. With synchronized, you cannot control the release of the lock. With the lock interface, you can lock () or unlock () as needed (). Daemon thread)
The so-called "daemon thread" means that as long as the program is still running, it should provide a public service thread in the background, but the daemon thread is not the core part of the program. Therefore, when all non-daemon threads are running, the program ends. On the contrary, as long as there are Non-daemon threads running, the daemon thread will not end. The correct method for stopping a thread (from think in Java 3rd edition chapter 13)
To reduce the likelihood of deadlocks, Java 2 abandons the stop (), suspend (), and resume () Methods of the thread class.
Stop () is abandoned because it does not release the lock of the object, so if the object is in an invalid state (that is, it is damaged ), other threads may see and modify it. The consequences of this problem may be very microseconds, so it is hard to detect. So don't use stop () Again. Instead, you should set a flag to tell the thread when to stop. The following is a simple example:
//: c13:Stopping.java
// The safe way to stop a thread.
import java.util.*;
ClassCanstop ExtendsThread {
// Must be volatile:
Private volatile Boolean stop = false; Private IntCounter = 0; Public VoidRun (){
While(! Stop & Counter <10000 ){
System. Out. println (counter ++ );
}
If(STOP)
System. Out. println ("detected stop ");
} Public VoidRequeststop (){
Stop = True;
}
} Public ClassStopping {
Public Static VoidMain (string [] ARGs ){
FinalCanstop stoppable = NewCanstop ();
Stoppable. Start ();
NewTimer ( True). Schedule ( NewTimertask (){
Public VoidRun (){
System. Out. println ("Requesting stop ");
Stoppable. requeststop ();
}
}, 500); // run () after 500 milliseconds
}
}///:~

Stop must be volatile so that the run () method can see it (otherwise it will use the local cache value ). The "task" of this thread prints 10,000 numbers, so when counter> = 10000 or someone wants it to stop, it ends. Note that requeststop () is not synchronized, because stop is both Boolean (to true is an atomic operation) and volatile.
After main () starts canstop, a timer is set to automatically call requeststop () in half a second (). The task of the true parameter in the timer constructor is to set this thread as a daemon thread so that it will not stop the program from exiting. Appendix: main methods of Thread
// JDK 1.4.2 _ 05 // native indicates implementation in other platform-dependent languages, such as C and Assembly // static method
Public static native void yield (); // pause the execution of the current thread to allow other threads to execute. Actually, you can get more CPU time.
Public static native void sleep (long millis) throws interruptedexception
Public static void sleep (long millis, int Nanos) throws interruptedexception // At present, only the millisecond level is implemented, and the nanoseconds only process those greater than 500000 as one millisecond.
Public static Boolean interrupted () // The difference with isinterrupted is that this will change the thread status to interrupted // synchronous method
Public synchronized native void start () // method that can be overwritten
Public void run ()
Public void interrupt ()
Public Boolean isinterrupted () // method that cannot be overwritten
Public final native Boolean isalive ()
Public final void setpriority (INT newpriority)
Public final int getpriority ()
Public final synchronized void join (long millis) throws interruptedexception
Public final synchronized void join (long millis, int Nanos) throws interruptedexception
Public final void join () throws interruptedexception // wait until the thread dies or until the specified wait time is reached to continue executing the following code
Public final void setdaemon (Boolean on) // set the thread to a daemon thread.
Public final Boolean isdaemon () attached: Object-related thread method
Public final void wait () throws interruptedexceptionwait // call wait (0)
Public final native void wait (long timeout) throws interruptedexception
Public final void wait (long timeout, int Nanos) throws interruptedexception // call wait (long timeout)
Public final native void Policy ()
Public final native void policyall () references about threads
1. Think in Java 3rd edition Chapter 13
2. Concurrent Programming in Java 2nd edition by Doug Lea, Addison-Wesley, published in 2000
3. Java threads 3rd by Scott Oaks, Henry Wong O 'Reilly, September 2004
4. programming for the Java Virtual Machine chapter 16
5. Java 2 primer plus chapter 18 p.s. This document is a brief summary of some concepts in Java multithreading and solutions to some problems!

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.