Java multithreaded Programming
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
threads, and each thread defines a separate execution path.
Multithreading is a special form of multitasking. Multithreading requires less overhead than multitasking.
Here you define another term related to threading: process: A process consists of memory space allocated by the operating system and contains one or more threads. A line
Cannot exist independently, it must be part of the process. A process runs until all non-waiting threads end up running.
Multithreading enables programmers to write very efficient programs to get the most out of the CPU, because the CPU's idle time is kept to a minimum.
Life Week of a thread
Threads pass through various stages of their life cycle. Shows the full life cycle of a thread.
New State : A newly generated thread starts its life cycle from the new state. It keeps this state know program start this thread.
running state : When a new state thread is started, the thread becomes operational and a thread is considered to be starting to perform its task in this state
Ready state : When a thread waits for another thread to perform a task, the thread goes into a ready state. When another thread gives the ready state
When a thread sends a signal, the thread is re-switched to the running state.
hibernation : The thread goes into hibernation from the running state because a thread has run out of time slices. When the time interval expires or the waiting time occurs
, the state of the thread switches to the running state.
terminating State : A running state of a thread completes a task or other termination condition occurs, and 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. Java priority in Min_priority (1) and
Within the range of max_priority (10). 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 time 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.
In order to implement the Runnable interface, a class only needs to execute a method call run (), declared as follows:
<span style= "FONT-SIZE:18PX;" >public void Run () </span>
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.
Several construction methods are defined in the thread class, and this is what we often use:
<span style= "FONT-SIZE:18PX;" >thread (Runnable threadob,string threadname);</span>
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.
<span style= "FONT-SIZE:18PX;" >void Start ();</span>
Instance
Here is an instance of creating a thread and starting to make it execute:
<span style= "FONT-SIZE:18PX;" >//Create a new thread class Newthread implements Runnable {thread T; Newthread () {///create second new thread t = new Thread (this, "Demo thread"); SYSTEM.OUT.PRINTLN ("Child thread:" + t); Start thread T.start (); }//second thread entry public void run () {try {for (int i = 5; i > 0; i--) {System.out.println ("Chil D Thread: "+ i); Pause thread Thread.Sleep (50); }} catch (Interruptedexception e) {System.out.println ("Child interrupted."); } System.out.println ("Exiting child Thread."); }}public class Threaddemo {public static void main (String args[]) {//Create a new thread for the Newthread (); try {for (int i = 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."); }}≪/span>
Compile the above program to run the following results:
to create a thread by inheriting the thread class
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
Here is an instance of creating a thread and starting to make it execute:
<span style= "FONT-SIZE:18PX;" >//create thread class Newthread extends Thread {newthread () {//Create a second new thread super ("Demo thread") SYSTEM.OUT.PRINTLN ("Child thread:" + this); Start the thread start (); }//second thread entry public void run () {try {for (int i = 5; i > 0; i--) {System.out.println ("Ch ILD Thread: "+ i); Let the thread hibernate for a while thread.sleep (50); }} catch (Interruptedexception e) {System.out.println ("Child interrupted."); } System.out.println ("Exiting child Thread."); }}} public class Extendsthread {public static void main (String args[]) {//Create a new thread, and Newthread (); try {for (int i = 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."); }}</span>
Compile the above program to run the following results:
Thread class method
The following table lists some important methods of the thread class:
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.
Instance
The following Threadclassdemo program demonstrates some of the methods of the thread class:
File name: Displaymessage.java
<span style= "FONT-SIZE:18PX;" >//creates a thread public class DisplayMessage implements runnable{private String message by implementing the Runnable interface ; Public DisplayMessage (String message) { this.message = message; } public void Run () { while (true) { System.out.println (message); } }} </span>
File name: Guessanumber.java
<span style= "FONT-SIZE:18PX;" >//creates threads public class Guessanumber extends thread{private int number by inheriting the thread class ; Construction method Public guessanumber (int number) { this.number = number; } public void Run () { int counter = 0; int guess = 0; do{ guess = (int) (Math.random () * + 1); System.out.println (This.getname () + "guesses" + guess); counter++; } while (guess! = number); SYSTEM.OUT.PRINTLN ("* * correct!" + this.getname () + "in" + Counter + "guesses.**");} } </span>
File name: Threadclassdemo.java
<span style= "FONT-SIZE:18PX;" >//Test Class Threadclassdemopublic class threadclassdemo{public static void Main (String [] args) {Runnable Hello = new DisplayMessage ("Hello"); Thread thread1 = new Thread (hello); Thread1.setdaemon (TRUE); Thread1.setname ("Hello"); System.out.println ("Starting Hello thread ..."); Thread1.start (); Runnable bye = new DisplayMessage ("Goodbye"); Thread thread2 = new Thread (bye); Thread2.setpriority (thread.min_priority); Thread2.setdaemon (TRUE); System.out.println ("Starting Goodbye thread ..."); Thread2.start (); System.out.println ("Starting thread3 ..."); Thread thread3 = new Guessanumber (27); Thread3.start (); try{Thread3.join (); }catch (interruptedexception e) {System.out.println ("Thread interrupted."); } System.out.println ("Starting thread4 ..."); Thread thread4 = new Guessanumber (75); Thread4.start (); System.out.println ("MaiN () is ending ... "); }}</span>
The results of the operation are as follows, and the results are different for each run.
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
multi-threaded use
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.
You need to use multithreaded programming.
Through the use of multithreading, you can write a very efficient program. However, please note that if you create too many threads, the efficiency of the program execution is actually
lowered, not lifted.
Keep in mind that the switching overhead of the context is also important if you create too many threads, the CPU spends more time switching the context than executing the program's
Time!
Java multithreaded programming