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 a special form of multitasking, but multithreading uses a much smaller resource overhead.
Here you define another term related to threading-process: a process that includes the memory space allocated by the operating system and contains one or more threads. A thread cannot exist independently, it must be part of a process. A process runs until all non-waiting threads end up running.
Multithreading can satisfy programmers to write high-efficiency programs to achieve the full use of CPU.
Life Week of a thread
Threads pass through various stages of their life cycle. 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.
- Death Status:
When a running state thread finishes a task or other termination condition occurs, the thread switches to the terminating state.
Priority of the thread
Each Java thread has a priority, which helps the operating system determine the order in which the threads are dispatched.
The priority of a Java thread is an integer whose value range is 1 (thread.min_priority)-Ten (thread.max_priority).
By default, each thread will be assigned a priority of norm_priority (5).
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.
Create a thread
Java provides two ways to create a thread:
- By implementing the Runable interface;
- By inheriting the thread class itself.
To create a thread by implementing the Runnable interface
The simplest way to create a thread is to create a class that implements the Runnable interface.
To implement Runnable, a class simply executes a method call to run (), declared as follows:
publicvoid run()
You can override this method, it is important to understand that run () can call other methods, use other classes, and declare variables, just like the main thread.
After you have created a class that implements the Runnable interface, you can instantiate a thread object in the class.
Thread defines several construction methods, and this is what we often use:
Thread(Runnable threadOb,String threadName);
Here, Threadob is an instance of the class that implements the Runnable interface, and ThreadName specifies the name of the new thread.
After the new thread is created, you call it's start () method before it runs.
void start();
Instance
Here is an instance of creating a thread and starting to make it execute:
//Create a new threadclassNewthreadImplementsRunnable {Thread t; Newthread () {//Create a second new threadt =NewThread ( This, "Demo Thread"); System.out.println ("Child Thread:" +t); T.start (); //Start Thread } //Second Thread entry Public voidrun () {Try { for(inti = 5; i > 0; i--) {System.out.println ("Child Thread:" +i); //pausing a threadThread.Sleep (50); } } Catch(interruptedexception e) {System.out.println ("Child interrupted."); } System.out.println ("Exiting child Thread."); }} Public classThreaddemo { Public Static voidMain (String args[]) {NewNewthread ();//Create a new thread Try { for(inti = 5; i > 0; i--) {System.out.println ("Main Thread:" +i); Thread.Sleep (100); } } Catch(interruptedexception e) {System.out.println ("Main thread interrupted."); } System.out.println ("Main thread exiting."); }}
Compile the above program to run the following results:
Child Thread:thread[demo thread,5,main]main thread:5child thread:5child thread:4main thread:4child thread:3child Thr Ead:2main thread:3child thread:1exiting child Thread. Main thread:2main thread:1main Thread exiting.
To create a thread by inheriting thread
The second way to create a thread 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.
Instance
//creating threads by inheriting threadclassNewthreadextendsThread {newthread () {//Create a second new thread Super("Demo Thread"); System.out.println ("Child Thread:" + This); Start (); //Start Thread } //Second Thread entry Public voidrun () {Try { for(inti = 5; i > 0; i--) {System.out.println ("Child Thread:" +i); //let the thread sleep for a whileThread.Sleep (50); } } Catch(interruptedexception e) {System.out.println ("Child interrupted."); } System.out.println ("Exiting child Thread."); }} Public classExtendthread { Public Static voidMain (String args[]) {NewNewthread ();//Create a new thread Try { for(inti = 5; i > 0; i--) {System.out.println ("Main Thread:" +i); Thread.Sleep (100); } } Catch(interruptedexception e) {System.out.println ("Main thread interrupted."); } System.out.println ("Main thread exiting."); }}
Compile the above program to run the following results:
Child Thread:thread[demo thread,5,main]main thread:5child thread:5child thread:4main thread:4child thread:3child Thr Ead:2main thread:3child thread:1exiting child Thread. Main thread:2main thread:1main Thread exiting.
Thread method
The following table lists some important methods of the thread class:
| 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. |
Tests whether the thread is active. The above method is called by the thread object. 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. |
Instance
The following Threadclassdemo program demonstrates some of the methods of the thread class:
//file name: Displaymessage.java//creating a thread by implementing the Runnable interface Public classDisplayMessageImplementsrunnable{PrivateString message; Publicdisplaymessage (String message) { This. Message =message; } Public voidrun () { while(true) {System.out.println (message); } }}//file name: Guessanumber.java//create a thread by inheriting the thread class Public classGuessanumberextendsthread{Private intNumber ; PublicGuessanumber (intNumber ) { This. Number =Number ; } Public voidrun () {intCounter = 0; intGuess = 0; Do{guess= (int) (Math.random () * 100 + 1); System.out.println ( This. GetName ()+ "guesses" +guess); Counter++; } while(Guess! =Number ); System.out.println ("* * correct!" + This. GetName ()+ "in" + Counter + "guesses.**"); }}//file name: Threadclassdemo.java Public classthreadclassdemo{ Public Static voidmain (String [] args) {Runnable Hello=NewDisplayMessage ("Hello"); Thread Thread1=NewThread (hello); Thread1.setdaemon (true); Thread1.setname ("Hello"); System.out.println ("Starting Hello thread ..."); Thread1.start (); Runnable Bye=NewDisplayMessage ("Goodbye"); Thread thread2=NewThread (bye); Thread2.setpriority (thread.min_priority); Thread2.setdaemon (true); System.out.println ("Starting Goodbye thread ..."); Thread2.start (); System.out.println ("Starting thread3 ..."); Thread thread3=NewGuessanumber (27); Thread3.start (); Try{thread3.join (); }Catch(interruptedexception e) {System.out.println ("Thread interrupted."); } System.out.println ("Starting thread4 ..."); Thread Thread4=NewGuessanumber (75); Thread4.start (); System.out.println ("Main () is ending ..."); }}
The results of the operation are as follows, and the results are different for each run.
Starting Hello thread ... Starting Goodbye thread ... HelloHelloHelloHelloHelloHelloHelloHelloHelloThread-2 guesses 27hello** correct! Thread-2 in 102 guesses.**hellostarting thread4 ... hellohello..........remaining result produced.
Several key concepts of threading:
In multithreaded programming, you need to understand the following concepts:
- Thread synchronization
- Inter-thread communication
- Thread deadlock
- Line programmed: Suspend, stop, and resume
Use of multithreading
The key to effective use of multithreading is to understand that programs are executed concurrently rather than serially. For example, there are two subsystems in the program that need to be executed concurrently, which requires multithreaded programming.
Through the use of multithreading, you can write a very efficient program. Note, however, that if you create too many threads, the efficiency of the program execution is actually reduced, not promoted.
Keep in mind that the context switching overhead is also important, if you create too many threads, the CPU spends more time switching the context than executing the program!
Java multithreaded Programming