One, the life cycle of the thread
A thread is a process that executes dynamically, and it also has a process from generation to death.
Shows the full life cycle of a thread
- New status:
When a thread object is established using the new keyword and the thread class or its subclasses, the thread object is in the new state. It keeps this state until the program start () this thread.
- Ready state:
When the thread object calls the start () method, the thread enters the ready state. The ready state thread is in the ready queue, waiting for the thread scheduler in the JVM to dispatch.
- Running Status:
If the ready state thread gets the CPU resources, it can execute run (), at which point the thread is in the running state. A running thread is the most complex and can become a blocking state, a ready state, and a dead state.
- Blocking Status:
If a thread executes a method such as sleep, suspend (hangs), and so on, the thread will enter a blocking state from the running state after the resource is lost. You can re-enter the ready state after the sleep time has arrived or the device resource has been acquired. Can be divided into three kinds:
Wait for blocking: the thread in the running state executes the wait () method, which causes the thread to enter a wait-blocking state.
Synchronous blocking: The thread acquires a synchronized synchronization lock failure (because the synchronization lock is occupied by another thread).
Other blocking: When an I/O request is made by the calling thread's sleep () or join (), the thread enters the blocking state. When the sleep () state times out, the join () waits for the thread to terminate or time out, or the I/O process completes and the thread is re-entered in a ready state.
- Death Status:
When a running state thread finishes a task or other termination condition occurs, the thread switches to the terminating state
Second, the priority of the thread
1, adjust the thread priority: Java thread has priority, high priority thread will get more running chance the priority of the Java thread is expressed in integers, and the value range is the 1~10,thread class has the following three static constants: the static int max_priority thread can have the most High priority with a value of 10. The static int min_priority thread can have the lowest priority, with a value of 1. The static int norm_priority The default priority assigned to the thread, with a value of 5. The SetPriority () and GetPriority () methods of the thread class are used to set and get the priority of the thread, respectively
A thread with a higher priority is more important to the program, and the processor resources should be allocated before a low-priority thread. However, thread precedence does not guarantee the order in which threads are executed, and is very dependent on the platform
Third, create a thread
Java provides three ways to create threads:
- By implementing the Runnable interface
- By inheriting the Thread class itself
- Creating threads from callable and future
1) Implement the Runnable interface to create the thread
The simplest way to create a thread is to create a class that implements the Runnable interface, in order to implement Runnable, a class only needs to execute a method call to run ()
first, create an object class Packagetest_synthronized; Public classFoo {intx=100; Public intGetX () {returnx;} Public intFixinty) {synchronized( This) {x=x-y; System.out.println ("Thread" +thread.currentthread (). GetName () + "run End, decrease" "+y+ "", the current value is: "+x);} returnx;}} Second, create a thread class Packagetest_synthronized;/*** thread synchronization and lock*/ Public classThread_synchronized_01Implementsrunnable{PrivateFoo foo=NewFoo (); Public Static voidMain (string[] args) {thread_synchronized_01 syn=Newthread_synchronized_01 (); Thread T1=NewThread (syn, "T1")); Thread T2=NewThread (syn, "T2")); T1.start (); T2.start (); } /*(non-javadoc) * @see Java.lang.runnable#run ()*/ Public voidrun () { for(inti = 0; I < 3; i++) { This. Fix (30); Try{Thread.Sleep (1); } Catch(interruptedexception e) {e.printstacktrace (); } /** T1: The x value of the current Foo object = t2: The x value of the current Foo object = T1: The x value of the current Foo object = -20 T2: The x value of the current Foo object =-50 T1: The x value of the current Foo object = -80 T2: The x value of the current Foo object =-80 * From the results, it is obvious that the output value is unreasonable. The reason is that two threads do not control access to Foo objects and modify their data as a result. If you want to keep the results reasonable, you only have to achieve one goal, which is to restrict the access to Foo, and only one thread at a time can access it. This will ensure that the data in the Foo object is reasonable. There are two things that need to be done in the Java code: identify the Resource class Foo variable x that is being accessed as private, synchronize the code that modifies the variable, and use the Synchronized keyword to synchronize the method or code. */System.out.println (Thread.CurrentThread (). GetName ()+ ": The x value of the current Foo object =" +foo.getx ()); } } Public intFixinty) {returnFoo.fix (y); }} III, result thread T1 run end, reduce "30 ", the current value is: 70T1: The x value of the current Foo object= 70thread T1 run end, reduce "30 ", the current value is: 40T1: The x value of the current Foo object= 40thread T1 run end, reduce "30 ", the current value is: 10T1: The x value of the current Foo object= 10thread T2 run end, reduce "30 ", the current value is:-20T2: The x value of the current Foo object=-20thread T2 run end, reduce "30 ", the current value is:-50T2: The x value of the current Foo object=-50thread T2 run end, reduce "30 ", the current value is:-80T2: The x value of the current Foo object=-80
2) inherit thread to create threads
The second method is to create a new class that inherits the Thread class and then creates an instance of the class.
The inheriting class must override the run () method, which is the entry point for the new thread. It must also call the start () method to execute.
Although this method is listed as a multi-threaded implementation, it is an example of implementing the Runnable interface in essence.
Packagetest_synthronized; Public classthread_synchronized_02 {
classMyThreadextendsthread{Privatefoo foo; /**Current Value*/ Private inty = 0; MyThread (String name, foo foo,inty) {Super(name); This. Foo =foo; This. y =y; } Public voidrun () {foo.fix (y); } } Public Static voidMain (string[] args) {thread_synchronized_02 run=Newthread_synchronized_02 (); Foo Foo=NewFoo (); MyThread T1= run.NewMyThread ("Thread A", Foo, 10); MyThread T2= run.NewMyThread ("Thread B", Foo, 2); MyThread T3= run.NewMyThread ("Thread C", Foo, 3); MyThread T4= run.NewMyThread ("Thread D", Foo, 5); T1.start (); T2.start (); T3.start (); T4.start (); }} result thread thread A runs to the end, reducing the "10 ", the current value is: 90thread C runs end, reduces "3 ", the current value is: 87Thread thread B runs the end, reducing the "2 ", the current value is: 85thread thread D ends, reduces "5 ", the current value is: 80
3) Creating threads through callable and future
1. Create an implementation class for the callable interface and implement the call () method, which will act as the thread execution body and have a return value.
2. Create an instance of the callable implementation class, using the Futuretask class to wrap the callable object, which encapsulates the return value of the call () method of the Callable object.
3. Use the Futuretask object as the target of the thread object to create and start a new thread.
4. Call the Get () method of the Futuretask object to get the return value after the child thread finishes executing
Packagetest_synthronized;Importjava.util.concurrent.Callable;Importjava.util.concurrent.ExecutionException;ImportJava.util.concurrent.FutureTask; Public classCallablethreadImplementsCallable<integer> { PublicInteger Call ()throwsException {inti = 0; for(; i<8;i++) {System.out.println (Thread.CurrentThread (). GetName ()+" "+i); } returni; } Public Static voidMain (string[] args) {callablethread callablethread=NewCallablethread (); Futuretask<Integer> ft=NewFuturetask<integer>(Callablethread); for(inti = 0;i < 8;i++) {System.out.println (Thread.CurrentThread (). GetName ()+ "The value of the loop variable i" +i); if(i==2) { NewThread (FT, "threads with return value")). Start (); } } Try{System.out.println ("The return value of the child thread:" +ft.get ()); } Catch(interruptedexception e) {e.printstacktrace (); } Catch(executionexception e) {e.printstacktrace (); }}} result main of the loop variable i value 0main of the loop variable I value 1main of the loop variable I value 2main of the value of the loop variable i 3 has the return value of the thread0The value of the loop variable I of main 4 has a thread that returns a value1The value of the loop variable I of main 5 has a thread that returns a value2The value of the loop variable I of main 6 has a thread that returns a value3The value of the loop variable I of main 7 has a thread that returns a value4thread with return value5thread with return value6thread with return value7The return value of the child thread:8
Iv. three ways to compare threads
1. When transcend multi-threading is implemented in a way that implements the Runnable, callable interface, the thread class simply implements the Runnable interface or callable interface and can inherit other classes.
2. When creating multi-threading in a way that inherits the thread class, writing is simple and if you need access to the current thread, you do not need to use the Thread.CurrentThread () method to get the current thread directly using this.
Java multithreaded Programming