Several important concepts of java multi-threaded
Java multi-threaded model diagram
From this we can see that all threads are running in JVM, and share a main memory (Global Memory in the figure), while each has its own work memory (Local variables in the figure). Understanding Java's basic memory model is important.
Java thread life cycle
1, New: Thread objects have been created, but have not yet started (START () method), so it cannot be run.
2. Runnable: After calling the start () method, the thread is in this state. Note that the thread is not in the Running state after Start (). Only the scheduling mechanism is assigned to it CPU time it enters the Running state.
3, Running: The CPU implementation dispatched the thread, then in the Running state.
4, Blocked: When the thread in the Running Status is triggered by Sleep (), Wait () or other reasons, it enters the Blocked state. At this time, it can be woken up by notify () or the like to the Scheduler of Scheduler, otherwise, nothing, stop there.
5, DEA D: When Run () is ended normally or is forced, the thread enters the DEAD state. At this time, 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 re-NEW.
Atomic operation and volatile keyword
The atomic operation is not an operation of the thread scheduling mechanism to be interrupted. In Java language, atomic operations for a variable are:
Use: Transfer the copy variable context in the thread working memory to the thread execution engine. This will happen as long as the thread performs a virtual machine command using a variable value.
Assign: Transfer the value in the thread execution engine to the copy variable in the thread working memory. This will happen as long as the thread performs a virtual machine command assigned to the variable.
READ: (executed on the main memory) Transmits the variable context in the main memory to the thread working memory so that the next LOAD operation is used.
LOAD: (executed on work memory) Transfer the value of the variable from the primary memory to the variable to the copy variable of the thread working memory.
Store: (executed on work memory) Transfer the context of the copy variable of the work memory to the main memory so that the next Write operation is used.
Write: (executed on the main memory) transmits the value of the variable from the thread work memory to the main memory to the main variable.
LOCK: (executed in the thread to be tightly synchronously synchronously) will result in a thread to get a request (similar count) on a special lock.
UNLOCK: (executed when the thread is tightly synchronously synchronously) causes the thread to release a required right in a specific lock.
The Volatile modifier is used to declare a variable to perform in the main memory instead of copying to work memory. This is the LOAD, Store, READ, and WRITE operations of the basic type of Volatile variables are atomic operations, and even if the type of variable is Double or Long. Then such an operation is the thread safe, no need for Synchronized lock mechanisms to ensure. However, if there are other code except for these operations, it is not an atomic operation, which will not ensure thread security. For example, incrementing or decrementing 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 the variable is always deposited from the primary, so that Volatile is negligible for those versions. However, with Java evolution, the current J2SE 5.0, the virtual machine's implementation has become more complex, and new memory models and optimization are introduced, and this is also a future trend. Under the realization of new virtual machine models, developers cannot assume that variables are directly accessed from the main memory. If you want the "atomic operation" of a variable to achieve thread security requirements, the safest way is to declare the variable as Vola Tile. What is the role of Volatile to array? The answer is that only the quote of the array is Volatile, and the elements of the array will still be stored in local memory. There is currently no way to specify the elements of the array to volatile. So, if you access an array element, you must use Synchronized to protect your data.
Lock and synchronized keyword In order to synchronize multithreading, the Java language uses a monitor (Monitors), a advanced mechanism to qualify only one thread to execute a code that is protected by a monitor. The monitor's behavior is implemented by a lock, and each object has a lock.
Each thread has a work memory that stores the variables copied from the main memory shared by all threads. In order to access a shared variable, a thread usually has to get a lock and refreshed its working memory, which will copy the shared value from the main memory to the work memory. When the thread is locked, the value in the work memory will return to the main memory.
& n BSP; a thread can get the lock of the object multiple times. That is, a Synchronized method calls another synchronized method, while the latter calls another Synchronized method, such as this. JVM will track the number of times the object is locked. If the object is not locked, its counter should be zero. When the thread gets the lock of the object, the counter is one. Each time the thread is a lock, the counter adds one. Of course, only the thread of the first acquisition of the object lock can get a lock multiple times. Every time the thread exits a Synchronized method, the counter is reduced. Wait, the object is unlocked, and this object can be used when other threads can be used.
In addition, each class has a lock (which is a class of class objects), which is not interfered with each other when the class Synchronized Static method reads STATIC data.
Never interact between threads, they only communicate through the main memory.
Starting from J2SE 1.5, Java has a LOCK interface, which will make the lock concept clearer, making the thread synchronization control easier. With SYNCHRONIZED, you can't control the release of the lock, and use the LOCK interface, you will be able to lock () or you need unlock ().
Daemon Thread "" daemon thread "refers to, as long as the program is still running, it should provide a thread for a public service in the background, but the guardian thread does not belong to the core part of the program. Therefore, when all the non-standard threads are running, the program is over. On the contrary, as long as there is a non-standard thread running, the guardian thread will not end.
Stop thread correct way (from Think in Java 3rd Edition Chapter 13)
In order to reduce the chance of deadlock, Java 2 abandoned Thread class STOP (), Suspend () and resume () method.
The reason is to give up STOP () because it does not release the lock of the object, so if the object is in an invalid state (that is, it is destroyed), other threads may see and modify it. The consequences of this problem may be very microseconds, so it is difficult to notice. So don't use STOP (). Instead, you should set a flag (FLAG) to tell the clutch when it should stop. Here is a simple example:
//: C13: stopping.java// The Safe Way to stop a thread.import java.util. *;
Class Canstop
Extends thread
{
// must be volatile: private volatile boolean stop = false;
Private
INT Counter =
0;
public
Void
Run ()
{
While (! stock && counter <
10000)
{
System.out.println (Counter );
}
IF (STOP)
System.out.println (
"Detected stop");
}
public
Void
Requeststop ()
{
STOP =
True;
}
}
public
Class Stopping
{
public
Static
Void
Main (String [] ARGS)
{
Final canstop stoppable =
New
CANSTOP ();
STOPPABLE.START ();
New
Timer
True).
Schedule
New
Timertask ()
{
public
Void
Run ()
{
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 is to print 10,000 numbers, so when counter> = 10000 or someone wants it to stop, it will end. Note that RequestStop () is not synchronized because STOP is both boolean (change to TRUE is an atomic operation) is Volatile.
MAIN () set a Timer after the Canstop was set, allowing it to automatically call RequestStop () over half. The task of the True parameter in the Timer's constructor is to set this thread into a daemon so that it will not prevent the program from exit.
Attached: Some main methods for thread
// jdk 1.4.2_05 // native means that other languages depend on the platform, such as C, compilation, etc.
// static method
Public static native void yield (); // Pause the execution of the current thread to allow other threads to execute. It actually enables yourself more CPU time.
Public Static Native Void Sleep (Long Millis) Throws InterruptedException
Public Static Void Sleep (Long Millis, int NANOS) throws interruptedException // Currently only to milliseconds, nanoseconds are only greater than 500,000 as 1 millisecond processing
Public static boolean interrupted () // The difference between IsInterrupted is this to change the state of the thread is an interrupted // synchronization method.
Public synchronized native void start ()
// Method for overwriting
Public void Run ()
Public void interrupt ()
Public Boolean IsInterrupted ()
// Methodible
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 // Waiting for thread death or to the specified wait time to continue the following code
Public final void setdaemon (Boolean on) // Set the thread to a daemon
Public Final Boolean Isdaemon ()
Attached: Object's approach to thread
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 // Implement call WAIT (long timeout)
Public Final Native Void Notify ()
Public Final Native Void NotifyAll ()
Reference information about threads
1, Think in Java 3rd Edition Chapter 13
2, Concurrent Programming in Java 2nd Edition author DOUG LEA, AddIn-Wesley, 2000 Publishing
3, Java Threads 3rd by Scott Oaks, Henry Wong O'Reilly, September 2004
4, programing for the Java Virtual Machine Chapter 16
5, Java 2 Primer Plus Chapter 18
P.S. This document is that I have to understand some of the concepts of Java multithreading and solve some simple summary, please advise!