The following is referenced from http://wiki.jikexueyuan.com/project/java/multithreading.html:
Java is a multithreaded programming language, which means that you can develop multithreaded programs in Java. A multithreaded application contains two or more parts that can be run in parallel, and each part is optimally utilized for the available resources, especially when the computer has multiple CPUs, while simultaneously resolving different tasks.
Multi-tasking means that multiple processes work together to handle shared resources such as CPUs. Multithreading extends the idea of multitasking to an application and can subdivide specific operations in a single application into separate threads. Each thread can run in parallel. The operating system divides processing time not only in different applications, but also in every thread in an application.
Multithreading can be programmed using a method that multiple activities can do in parallel in the same program.
One, the life cycle of the thread
A thread passes through different stages in its life cycle. For example, a thread is generated, starts, runs, and then dies. The following diagram shows the full life cycle of a thread.
Old version:
New:
The above mentioned stage explains in this:
- NEW: A fresh thread starts its life cycle in a new state. It always stays in this state until the program starts the thread. It is also known as a generated process.
- Runnable: After a newly generated thread has started, the thread becomes operational. Threads in this state are considered to be performing tasks.
- Waiting: Sometimes a thread jumps to a wait state while it waits for another thread to work. A thread only jumps back to a running state when another line Cheng the signal to the waiting thread to continue execution.
- Timed waiting: A Running thread can enter a timed wait state to wait for a specified time interval. A thread in this state of transition jumps back to its operational state when the time interval dies or when the activity it waits for occurs.
- Terminated (Dead): A running thread that enters the Terminated state when it finishes its task, or it ends.
Second, Thread priority
Each Java thread has a priority that helps the operating system determine the order of thread scheduling.
The Java thread's priority is within the range of min_priority (a constant of 1) and max_priority (a constant of 10). By default, each thread is given a priority norm_priority (a constant of 5).
A thread with a higher priority is more important for a program and should be assigned processing time before a low-priority thread. However, thread priority does not guarantee thread execution and the platform on which it depends.
Third, create a thread by implementing the Runnable interface
If a class is intended to be executed as a thread, it can be achieved by implementing the Runnable interface. There will be three basic steps to follow:
Step One:
As a first step, you need to implement the run () method provided by the Runnable interface. This method provides the entry point for the thread and puts the full business logic into the method. The following is the simple run () method syntax:
Public void Run ()
Step Two:
In the second step, you instantiate a Thread object using the following constructor:
Thread (Runnable threadobj, String threadname);
Threadobj is an instance of the class that implements the Runnable interface, and ThreadName is the name of the new thread.
Step Three:
Once the thread object is created, you can start it by calling the start () method of the Run () method. The following is a simple syntax for the start () method:
void start ();
Example:
Here is an example of creating a new thread and making it run:
classRunnabledemoImplementsRunnable {PrivateThread t; PrivateString ThreadName; Runnabledemo (String name) {ThreadName=name; System.out.println ("Creating" +threadname); } Public voidrun () {System.out.println ("Running" +threadname); Try { for(inti = 4; i > 0; i--) {System.out.println ("Thread:" + ThreadName + "," +i); //Let the thread sleep for a while.Thread.Sleep (50); } } Catch(interruptedexception e) {System.out.println ("Thread" + ThreadName + "interrupted."); } System.out.println ("Thread" + ThreadName + "exiting."); } Public voidstart () {System.out.println ("Starting" +threadname); if(T = =NULL) {T=NewThread ( This, ThreadName); T.start (); } }} Public classTestthread { Public Static voidMain (String args[]) {Runnabledemo R1=NewRunnabledemo ("Thread-1"); R1.start (); Runnabledemo R2=NewRunnabledemo ("Thread-2"); R2.start (); } }//this will produce the following results:Creating Thread-1starting Thread-1Creating Thread-2starting Thread-2Running Thread-1Thread:thread-1, 4Running Thread-2Thread:thread-2, 4Thread:thread-1, 3Thread:thread-2, 3Thread:thread-1, 2Thread:thread-2, 2Thread:thread-1, 1Thread:thread-2, 1Thread Thread-1exiting. Thread Thread-2 exiting.
Iv. creating threads by inheriting the thread class
The second way to create a thread is to create a new class that inherits the thread class by using the following two simple steps. This approach provides more flexibility in solving multithreaded problems created using a workable approach in the thread class.
Step One:
will need to overwrite the run () method available in the thread class. This method provides a portal for the thread and will put the full business logic into the method. The following is a simple syntax for the run () method.
Public void Run ()
Step Two:
Once the thread object is created, you can start it by calling the start () method of the Run () method. The following is a simple syntax for the start () method:
void start ();
Example:
This is the previous rewrite of the thread-inheriting program:
classThreaddemoextendsThread {PrivateThread t; PrivateString ThreadName; Threaddemo (String name) {ThreadName=name; System.out.println ("Creating" +threadname); } Public voidrun () {System.out.println ("Running" +threadname); Try { for(inti = 4; i > 0; i--) {System.out.println ("Thread:" + ThreadName + "," +i); //Let the thread sleep for a while.Thread.Sleep (50); } } Catch(interruptedexception e) {System.out.println ("Thread" + ThreadName + "interrupted."); } System.out.println ("Thread" + ThreadName + "exiting."); } Public voidstart () {System.out.println ("Starting" +threadname); if(T = =NULL) {T=NewThread ( This, ThreadName); T.start (); } }} Public classTestthread { Public Static voidMain (String args[]) {Threaddemo T1=NewThreaddemo ("Thread-1"); T1.start (); Threaddemo T2=NewThreaddemo ("Thread-2"); T2.start (); } }//this will produce the following results:Creating Thread-1starting Thread-1Creating Thread-2starting Thread-2Running Thread-1Thread:thread-1, 4Running Thread-2Thread:thread-2, 4Thread:thread-1, 3Thread:thread-2, 3Thread:thread-1, 2Thread:thread-2, 2Thread:thread-1, 1Thread:thread-2, 1Thread Thread-1exiting. Thread Thread-2 exiting.
Five, the thread method
The following is a list of important methods that can be obtained in the thread class.
| interface |
description |
| Methods with description |
starts a thread in a separate execution path, and then calls the run () method on the Thread object. |
| public void Run () |
If the thread object is instantiated with a separate runnable target, the run () method is called by the Runnable object. |
| public final void SetName (String name) |
changes the name of the thread object. There is also a getname () method to retrieve the name. |
| public final void setpriority (int precedence) |
sets the priority of the thread object. The possible values are between 1 and 10. |
| public final void Setdaemon (Boolean on) |
A truth value that flags this thread as a daemon. |
| public final void join (long millisec) |
The current process calls this method on the second thread, causing the current process to block until the second thread is terminated or the specified number of milliseconds has elapsed To. |
| public void interrupt () |
interrupts the process, and if it is blocked for any reason, it continues to execute. |
| Public Final Boolean isAlive () |
If the thread is alive and returns true, it can be started but at any time before it runs to completion. |
The previous method was called by a special thread object. The following methods in the thread class are static. Calling a static method performs an operation on the currently running thread.
| Interface |
Description |
| public static void Yield () |
Causes the currently running thread to yield to any other thread that is waiting to be dispatched at the same priority level. |
| public static void sleep (long millisec) |
Causes the currently running thread to block at least the specified number of milliseconds. |
| public static Boolean Holdslock (Object x) |
Returns true if the current thread holds a lock on a given object. |
| public static Thread CurrentThread () |
Returns a reference to the currently running thread, that is, the thread that called the method. |
| public static void DumpStack () |
Prints a stack trace for the currently running thread, which is useful when debugging multithreaded applications. |
Example:
The following Threadclassdemo program shows some methods of the thread class. Consider implementing the class DisplayMessage for runnable:
//File Name:DisplayMessage.java//Create a thread to implement Runnable Public classDisplayMessageImplementsrunnable{PrivateString message; Publicdisplaymessage (String message) { This. Message =message; } Public voidrun () { while(true) {System.out.println (message); } }}
The following is another class that inherits the thread class:
//File Name:GuessANumber.java//Create a thread to EXTENTD thread 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.**"); }}
The following are the main programs that use the classes defined above:
//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 ..."); }}
This will produce the following results. You can try this example one at a time and get different results each time.
Starting Hello thread ... Starting Goodbye thread ... Hellohellohellohellohellohellogoodbyegoodbyegoodbyegoodbyegoodbye .....
Test Project: Https://github.com/easonjim/5_java_example/tree/master/javabasicstest/test28
Multithreading in Java