Overview
Java provides built-in support for multithreaded programming. A multithreaded function contains two or more parts that can run concurrently. Each part of the program is called a thread, and each thread defines a separate execution path. Multithreading is also used to make full use of server resources and improve work efficiency.
Thread life cycle
A thread is a process that executes dynamically, and it also has a process from generation to death.
- 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.
Thread creation
Java provides three types of execution dependent classes for creating threads: implementing Runnable interfaces, inheriting the thread class, callable, and future creation threads;
Where callable and future creation threads are able to get the values returned by the thread, using the process:
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 execution ends.
Package Commclass;import Java.util.concurrent.callable;import java.util.concurrent.executionexception;import Java.util.concurrent.FutureTask; Public classThreaclass { Public Static voidThreastart () {Thread TR=NewThread (NewRunabledemo (),"Hellothead"); Tr.start (); Thread TR2=NewThread (NewThreaddemo ("NumTHread1")); Tr2.start (); Thread TR3=NewThreaddemo ("NumTHreadTV9"); Tr3.start (); Threadcall Tcall=NewThreadcall (); Futuretask<Integer> str=NewFuturetask<>(Tcall); Thread THR4=NewThread (str,"has a return value"); Thr4.start (); Try{System. out. println ("return the output result:"+str.Get()); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(executionexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } }}/** * @ClassName: Runabledemo * @Description: Inherit runable interface * @author Jiajinhao * @date March 2, 2017 pm 9:07:27 **/classRunabledemo implements runnable{@Override Public voidrun () { for(intI=0;i<5; i++) {System. out. println ("Hello:"+i+", current thread name:"+Thread.CurrentThread (). GetName ()); Try{Thread.Sleep ( +); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } } } }/** * @ClassName: Threaddemo * @Description: Method body Inheriting thread implementation * @author a18ccms a18ccms_gmail_com * @date March 2, 2017 9:11: **/classThreaddemo extends Thread { PublicThreaddemo (String threadname) { This. SetName (ThreadName); } @Override Public voidrun () {//TODO auto-generated Method Stub for(intI=0;i<5; i++) {System. out. println ("output result ID:"+i+Thread.CurrentThread (). GetName ()); } super.run (); } }classThreadcall Implements Callable<integer>{@Override PublicInteger Call () throws Exception {//TODO auto-generated Method Stub inti =0; for(;i< -; i++) {System. out. println (Thread.CurrentThread (). GetName () +" "+i); } returni; } }
Common methods of Thread class
Here is an example method:
Serial Number |
Method Description |
1 |
public void Start () Causes the thread to start executing, and theJava virtual machine calls the thread's Run method. |
2 |
public void Run () If the thread is constructed using a standalone Runnable run object, the Run method of the Runnable object is called, otherwise the method does nothing and returns. |
3 |
Public final void SetName (String name) Change the thread name so that it is the same as the parameter name. |
4 |
Public final void SetPriority (Int. priority) The priority of the thread to be rerouted. |
5 |
Public final void Setdaemon (Boolean on) Mark the thread as either a daemon thread or a user thread. |
6 |
Public final void Join (long millisec) The maximum time to wait for the thread to terminate is Millis milliseconds. |
7 |
public void Interrupt () The thread is disconnected. |
8 |
Public Final Boolean isAlive () Tests whether the thread is active. |
The following method is a static method of the thread class:
Serial number |
Method description |
1 |
public static void Yield () Pauses the currently executing thread object and executes other threads. |
2 |
public static void sleep (long millisec) Lets the currently executing thread hibernate (suspends execution) within the specified number of milliseconds, which is affected by the accuracy and accuracy of the system timer and scheduler. |
3 |
public static Boolean Holdslock (Object x) Returns true if and only if the monitor lock is persisted on the specified object by the front thread. |
4 |
public static Thread CurrentThread () Returns a reference to the currently executing thread object. |
5 |
public static void DumpStack () Prints the stack trace of the current thread to the standard error stream. |
Java Fundamentals-Multithreaded programming (v)