Java Multi-Threading two
The life cycle of a thread:
When a thread is created and started, it is neither a start-up nor an execution state, it goes through new (new), Ready (Runnable), run (Running), Block (Blocked), Dead (death) in the lifetime of the threads.
When a thread is started, it cannot always occupy the CPU to run alone, and all CPUs need to switch between multiple threads, so the thread will run more than once. Switch between ready.
New and ready states
When a program creates a thread with the new keyword, the thread is in the new state, and as with other Java objects, only the virtual machine allocates memory and initializes the value of the member variable. At this point the thread object does not show any dynamic characteristics of the thread, and the program does not execute threads on the thread execution body.
When the thread object calls the start () method, the thread is in a ready state, the Java virtual opportunity creates a method call stack and a program counter for it, and the thread that is in that State does not start executing, only indicating that the thread can run, and when the thread is running, depends on the JVM's dispatch.
The start thread calls the Start method, not the Run method, never calls the thread's Run method, and if the Run method is called, the thread object is treated as a normal object, and the executing body of the thread is called as a normal method!
After the run method is called, the thread is not in the new state, and the thread's Start method is not called again!
The Start method can only be used in Java for a thread that is in the new state, or a Illegalthreadstateexception exception will be thrown!
If you want to invoke the child thread's start () method immediately after the child thread begins execution, you can use Thread.Sleep (1) to let the currently running thread (the main thread) sleep for one millisecond, so that the CPU immediately starts another thread in a ready state, and it is important to note that Using the Thread.Sleep () method requires declaring the Interruptedexception exception!
Running and blocking states:
When there are several situations such as the following, it will enter the blocking state:
When a thread calls the sleep method to voluntarily discard the consumed processor resources
The thread calls a blocking Io method, and the thread is blocked until the method returns
The thread attempted to obtain a synchronization monitor, but the synchronization monitor is being held by another thread lock
Thread is waiting for a notification (notify)
The program calls the thread's suspend method to suspend the thread
When the above situation occurs, the following conditions will re-enter the ready state
Call The Sleep () method over a specified time
thread Call Blocking when Io method still returns
The thread succeeded in obtaining the synchronization monitor that was trying to get
now waiting for a notification while the other thread is sending a notification
a thread in the suspended state is called the Resume () method
The thread can only enter a ready state from the blocking state and cannot go directly to the running state. Transitions between ready and running States are usually not controlled by program control, but are determined by the scheduling of system threads.
Calling the yield () method allows the thread at run time to go into a ready state.
Thread death:
The thread will end in the following three ways, ending in a dead state
Run or call method execution complete, program end
The thread throws an uncaught exception or error
Call the thread's Stop method directly to end the thread
When the main thread ends, other threads are unaffected and do not end with it. Once the child thread starts up, he will have the same status as the main thread, which will not be affected by the main thread.
In order to test whether a thread is dead, you can call the thread's IsAlive method, return True when the thread is ready, run, block three states, and return False when the thread is new and dies in two states.
Do not attempt to invoke the Start method on a dead thread to restart it, and the thread after the death cannot be used as a thread.
If a thread in a non-new state uses the Start method, a Illegalthreadstateexception exception is thrown.
Control Threads:
Join Thread:
Thread provides a method--join method that lets one thread wait for another thread to finish, and when a join method of another thread is called in a program execution stream, the calling thread is blocked until the join thread joined by the Join method finishes executing.
The join method is usually called by a program that uses the thread to make the big problem a lot of small problems, each small problem is assigned a thread, and when all the small problems are processed, the main thread is called to do the next step!
Package Test1;public class Jointhread extends thread{public jointhread (String name) { super (name); } @Override public Void Run () {for (int i = 0; I <10; i++) { System.out.println (getName () + "" +i); c10/>} }}package Test1;public class Test {public static void main (string[] args) throws Interruptedexception { The new Jointhread ("Fresh Thread"). Start (); for (int i = 0; I <10; i++) { if (i==5) { jointhread j1=new jointhread ("thread being join"); J1.start (); J1.join (); } System.out.println (Thread.CurrentThread (). GetName () + "" +i);}}
Before the thread of the join is executed, two threads are executed alternately, and the main thread waits until the thread of the join executes, and the main thread continues execution!
Background thread:
There is a thread that runs in the background and whose task is to provide services to other threads, which are called background threads (Daemon thread), or daemon threads. The JVM's garbage collector is a typical background process.
The current thread is all dead, and the background thread will die automatically.
Calling the Setdaemon (ture) method of the thread can set the specified thread to be a background thread.
When the entire virtual machine is left with only a background thread, the program is not required to run, and all virtual machines will exit
The thread class also provides a Isdaemon method that specifies whether the thread is a background thread!
The foreground created by the line Cheng is considered a foreground thread, and the latter creates a line Cheng that is considered a background thread.
When the foreground thread dies, the JVM notifies the background thread that it is dead, but it takes a while for it to respond from receiving the instruction to making a response. In addition, if you want to set a thread as a background thread, you must set it before the thread starts
, that is, Setdaemon (true) must be called before the Start method, or a Illegalthreadstateexception exception will be thrown.
Thread Sleeping: Sleep
When the current thread calls the sleep method into a blocking state, the thread does not get an opportunity to execute during its sleep time
Even if there are no other executable threads in the system, the sleep thread will not execute, so the sleep method is often used to halt the execution of the program!
Thread Concessions:
Yield causes the thread to pause, but it does not block the thread, it simply transfers the thread to the ready state, that is, the yield method simply pauses the current thread, allowing the system's thread scheduler to reschedule again, which is entirely possible-after a thread invokes yield, The thread scheduler also calls it out to execute
In a multi-CPU parallel environment, the yield function is sometimes not obvious
The difference between the sleep () method and the yield method:
The Sleep method suspends the current thread and gives other threads an opportunity to take precedence over other threads, but the yield method then gives the same priority or higher priority thread execution opportunity.
The sleep method turns the thread into a blocking state until the blocking time is turned into a ready state, and the yield method does not go into a blocking state, only forcing the current thread into a ready state
The sleep method declaration throws a interruptedexception exception, and all calls to the sleep method will catch this exception, and the yield method does not
The sleep method has a better execution than the yield method!
To change the priority of a thread:
Each thread has a certain priority, and higher priority threads will have more execution opportunities
The default priority for each thread is the same as the parent process that created it, by default the main process has a normal priority
The thread class provides the setpriority (int newpriority) and getpriority () methods to set and return the priority of the thread where the setpriority parameter is of type int, ranging from 0 to 10
The thread class has three static constants: Max_priority:10 min_priority:1 Norm_priority:5
Thread synchronization:
Synchronizing code blocks:
Synchronize (obj) {}
OBJ: Synchronization monitor, meaning: When a thread starts executing a synchronous code block, it must first obtain a lock on the synchronization listener
only one thread can get a lock on the synchronization monitor at any time, and when the synchronization code block finishes executing, the thread releases the lock on the synchronization monitor.
Although Java programs allow any object to be used as a synchronization listener, it is generally recommended to use shared resources that may be concurrently accessed as synchronization monitors. Synchronization method: With the synchronous code block, Java Multithreading Security Support also provides a synchronization method, the synchronization method is to use a synchronized keyword to decorate a method, the method is called the synchronization method. For methods that are synchroize modified (not static methods), the synchronization monitor of the synchronous method is not required to display the specified synchronization monitor, which is the object that invokes the method call
The Synchronized keyword can be decorated with methods that can decorate blocks of code, but cannot decorate constructors, member variables. A thread-safe class has the following characteristics: objects of that class can be safely accessed by multiple threads each thread will get the correct results after invoking either method of the object the state of the object remains in a reasonable state after each thread invokes either method of the object
Package Test2;public class Account {private String accountno; private double balance; Public account () {} public account (String Accountno, double balance) {accountno = Accountno; This.balance = balance; }public String Getaccountno () {return accountno;} Public double GetBalance () {return balance;} public void Setaccountno (String accountno) {accountno = Accountno;} public void setbalance (double balance) {this.balance = balance;} Public synchronized void Draw (double drawcount) {if (Balance>=drawcount) {System.out.println (T Hread.currentthread (). GetName () + "withdrawal successful, take out" +drawcount+ "Yuan"); try {thread.sleep (1); } catch (Interruptedexception e) {//TODO auto-generated catch block E.printstacktrace (); } Balance-=drawcount; System.out.println ("Balance:" +balance); } else {System.out.println (Thread.CurrentThread (). GetName () + "" + "insufficient balance"); }} public int hashcode () {return accountno.hashcode (); } public boolean equals (Object obj) {if (this==obj) return true; if (Obj!=null&&obj.getclass () ==account.class) {account a= (account) obj; Return A.getaccountno (). Equals (Accountno); } return false; }}
Package Test2;public class Test extends Thread { private account account; Private double drawaccount; /** * @param account * @param drawaccount * /Public Test (String name,account account, double Drawaccount) { super (name); This.account = account; This.drawaccount = Drawaccount; } @Override public Void Run () { account.draw (drawaccount); } public static void Main (string[] args) {account a=new account ("3242332", +); Test t1=new Test ("a", A, b); Test t2=new Test ("B", A, +); T1.start (); T2.start (); } }
The thread safety of a mutable class is at the expense of operating efficiency, and in order to reduce the negative impact of line Shuo full lock, the following strategies can be adopted:
do not synchronize all the methods in a thread-safe class, only those that will change the competing resource (the competing resource is the shared resource).
if the variable class has both single-threaded and multi-threaded environments, provide two versions of the Mutable class (thread-safe and thread-insecure editions)This is the case with StringBuffer and StringBuilder, which should be used on a single thread when StringBuilder is used, and stringbuffer when multi-threading.
Release the lock on the sync monitor
The thread releases the lock on the synchronization listener in the following situations:
the synchronization method of the current thread, the execution of the synchronization code block, and the current thread release the synchronization listener.
The current thread has encountered a break, continue in a synchronous code block, a synchronous method, terminated the code block, the method runs, and the current thread freed the synchronization listener.
The current thread has encountered an unhandled error, exception, in the synchronous code block, synchronous method, causing the code block, the method to end unexpectedly, and the current thread releasing the synchronization listener.
when the current thread executes a synchronous code block or synchronous method, the program executes the Wait () method of the synchronization listener object, the current thread pauses, and the synchronization listener is released.
The thread does not release the synchronization listener in the scenario shown below:
when a thread executes a synchronous code block or synchronous method, the program calls the Thread.Sleep (), Thread.yield () method to suspend execution of the current thread, and the current thread does not release the synchronization monitor.
when a thread executes a synchronous code block, other threads call the thread's suspend () method to suspend the method, and the thread does not release the synchronization listener. (All programs should avoid using suspend and resume to manipulate threads)
Sync Lock (Lock)Starting with Java5, Java provides a more powerful thread-synchronization mechanism-synchronization is achieved by explicitly defining a synchronization lock object, in which the lock object acts as a synchronous lock. Lock provides a wider range of locking operations than the Synchronized method and synchronized code blocks, and lock allows for a more flexible structure, can have very different properties, and supports multiple related condition objects. Locks provide exclusive access to shared resources, and each time only one thread locks the lock object, the thread should obtain the lock object before it begins accessing the shared resource. Some locks may allow concurrent access to shared resources, such as Readwritelock (read-write locks), lock, Readwritelock is the two root interface provided by JAVA5, and does not provide a reetrantlock (Reentrant lock) implementation class. Provides a Reentrantreadwritelock implementation class for Readwritelock. JAVA8 new Strampedlock class, which can replace traditional reentrantreadwritelock in most scenarios. The Reentrantreadwritelock provides three lock mode--writing,readingoptimistic,reading. In the implementation of thread-safe control, more commonly used reentrantlock. Use this object to explicitly locking, release the lock. Using the Reentrantlock object for synchronization, with lock and release locks appearing at different scopes, it is generally advisable to use the finally block to ensure that locks are released when necessary.
Reentrantlock locks are reentrant, which means that a thread can lock the locked reentrantlock again, and the Reentrantlock object maintains a counter to track nested calls to the lock () method. After each call to lock (), the thread must explicitly call unlock () to release the lock, so a locked code can invoke another method that is protected by the same lock.
personal Understanding, the so-called lock, that is, within the scope of the lock must be executed one time, can not suspend and execute other threads.
dead Lock
Deadlocks occur when two threads wait for each other to release the Sync Monitor, and the Java Virtual Machine does not monitor and handle deadlocks, so be sure to avoid deadlocks.
Once a deadlock occurs, the entire program does not have any exceptions, and no hints are given, except that all threads are blocked and cannot continue.
However, deadlocks can occur easily, especially if there are multiple synchronization listeners in the system.
because the Suspend () method of the thread class can also easily lead to deadlocks, all Java is no longer recommended to use this method to pause thread execution.
Java Multi-Threading