Java Study Notes 15 -- multithreading programming basics 2, 15 -- multithreading Programming
URL: http://www.cnblogs.com/archimedes/p/java-study-note15.html.
Thread Lifecycle
1. Thread Lifecycle
The process from generation to elimination of threads
A thread is in a thread state at any time)
Thread lifecycle status chart
Birth status
The thread has just been created.
Readiness status
The start method of the thread has been executed.
The thread is ready to run
Running status
The processor is allocated to the thread and the thread is running.
Blocked)
When the thread sends an input/output request, it must wait for its return
When a method marked with synchronized is encountered and its Monitor is not obtained
Sleeping)
Run the sleep method and enter sleep.
Death status
Thread completed or exited
2. deadlock
Deadlock
When a thread is running, a certain step usually needs to meet certain conditions to continue. If this condition cannot be met, the thread will be blocked on this step.
Thread A may be stuck in waiting for thread B, while thread B is also stuck in waiting for thread C, and so on. The entire waiting chain may return to thread A at the end. In this way, the system is stuck in a loop of waiting for each other, and no thread can be moved. This is called a deadlock (deadlock)
For the deadlock problem, the key is not debugging after the problem occurs, but prevention.
Imagine a game where three people stand on the three vertices of a triangle, with three balls on the three sides ,. Everyone must get the ball on the left hand side before they can get the ball on the right hand side. After both hands have the ball, they can put both balls down.
Create three threads to simulate the actions of three players.
Class bils {boolean flag0 = false; // The flag variable of the 0 ball. true indicates that the ball has been taken; false indicates that no one has taken the boolean flag1 = false; // The flag variable boolean flag2 = false; // The flag variable} class Player0 extends Thread {// class private ballball of player 0; public Player0 (ballb) {this. ball = B;} public void run () {while (true) {while (ball. flag1 = true) {} // if the ball 1 has been taken away, wait for the ball. flag1 = true; // pick up the ball 1 while (ball. flag0 = true) {} // if the ball 0 has been taken away, wait for if (ball. Flag1 = true & ball. flag0 = false) {ball. flag0 = true; // pick up System. out. println ("Player0 has got two bils! "); Ball. flag1 = false; // put the ball No. 1 down. flag0 = false; // put the 0 ball down. try {sleep (1); // put it down and rest for 1 ms} catch (Exception e) {}}}} class Player1 extends Thread {// class private ballball of Player 1; public Player1 (ballb) {this. ball = B;} public void run () {while (true) {while (ball. flag0 = true) {} ball. flag0 = true; while (ball. flag1 = true) {}if (ball. flag0 = true & ball. flag1 = false) {ball. flag1 = true; Sy Stem. out. println ("Player0 has got two bils! "); Ball. flag0 = false; ball. flag1 = false; try {sleep (1);} catch (Exception e) {}}}} class Player2 extends Thread {// class private ballball of Player 2; public Player2 (ballb) {this. ball = B;} public void run () {while (true) {while (ball. flag2 = true) {} ball. flag2 = true; while (ball. flag1 = true) {}if (ball. flag2 = true & ball. flag1 = false) {ball. flag1 = true; System. out. println ("Player0 h As got two bils! "); Ball. flag2 = false; ball. flag1 = false; try {sleep (1);} catch (Exception e) {}}} public class playball {public static void main (String [] args) {bballs ball = new bballs (); // create a ball object Player0 p0 = new Player0 (ball); // create Player1 p1 = new Player1 (ball ); // create Player No. 1 Player2 p2 = new Player2 (ball); // create Player No. 2 startup start (); // start Player No. 0 p1.start (); // start player p2.start (); // start PLAYER 2 }}
Running result:
After several times, the system will be deadlocked and no output information is available, that is, no one can have both sides of the ball at the same time.
Program description:
If three people get the ball on the left hand side and wait for the ball on the right hand side, then because no one can let go, the three threads will all be waiting, this constitutes a deadlock.
To facilitate the observation of conditions for deadlocks, we added the sleep statement after each player put the balls on both sides.
To avoid deadlocks, You need to modify the rules of the game so that everyone can only grab the Small Medium balls on both sides before getting the other ball, so that no deadlock will occur.
3. Control the thread life
End thread life
The stop method can end the thread's life.
However, if a thread is operating on the shared data segment and the stop operation ends when the operation is not completed, data integrity may occur. Therefore, this method is not recommended.
Generally, you can end a thread by controlling the cyclic conditions in the run method.
The thread continuously displays an increasing integer. Press the Enter key to stop running:
Class TestThread1 extends Thread {private boolean flag = true; public void stopme () {// control the loop condition flag = false in this method;} public void run () {int I = 0; while (flag) {System. out. println (I ++); // if the flag is true, the incremental integer is always displayed.} public class ext8_12 {public static void main (String [] args) throws IOException {TestThread1 t = new TestThread1 (); t. start (); new BufferedReader (new InputStreamReader (System. in )). readLine (); // wait for the keyboard to input t. stopme (); // call the stopme method to end the t thread }}
The running effect is to stop displaying after pressing the Enter key.
Thread priority
Thread Scheduling
In a single CPU system, multiple threads need to share the CPU. at any point in time, only one thread is running.
Controlling multiple threads to run in a certain order on the same CPU is called thread scheduling.
Java Virtual Machine supports a very simple and definite scheduling algorithm, called a fixed priority algorithm. This algorithm schedules a thread based on its priority.
Thread priority
Each Java thread has a priority in the range of 1 and 10. By default, the priority of each thread is set to 5.
The new thread object B created during thread A running. The initial state has the same priority as thread.
If A is A background thread, B is also A background thread.
You can use the setPriority (int priority) method to change the original priority at any time after the thread is created.
Thread Scheduling Based on thread priority
A thread with a higher priority takes priority in execution than a thread with a lower priority.
For threads with the same priority, Java processing is random.
The underlying operating system may support less than 10 priorities, which may cause some confusion. Therefore, priority can only be used as a rough tool. The final control can be done by wise using the yield () function.
We can only use the thread priority based on efficiency considerations, rather than relying on the thread priority to ensure the correctness of the algorithm.
If a thread is running, it will be paused only when one of the following conditions occurs:
A thread with a higher priority changes to the Ready state (Ready );
Blocking occurs due to input/output (or other reasons), sleep calling, wait, and yield methods;
For systems that support time slice, the time slice expires.
Example: create two threads with different priorities, all increasing from 1 to 400000, each increase of 50000 is displayed once
Class TestThread2 extends Thread {private int tick = 1; private int num; public TestThread2 (int I) {this. num = I;} public void run () {while (tick <400000) {tick ++; if (tick % 50000) = 0) {// display System at intervals of 50000. out. println ("Thread #" + num + ", tick =" + tick); yield (); // give up execution permission }}} public class ext8_13 {public static void main (String [] args) {TestThread2 [] runners = new TestThread2 [2]; for (int I = 0; I <2; I ++) runners [I] = new TestThread2 (I); runners [0]. setPriority (2); runners [1]. setPriority (3); for (int I = 0; I <2; I ++) runners [I]. start ();}}
The running result is as follows:
Thread #1, tick = 50000
Thread #1, tick = 100000
Thread #1, tick = 150000
Thread #1, tick = 200000
Thread #1, tick = 250000
Thread #1, tick = 300000
Thread #1, tick = 350000
Thread #1, tick = 400000
Thread #0, tick = 50000
Thread #0, tick = 100000
Thread #0, tick = 150000
Thread #0, tick = 200000
Thread #0, tick = 250000
Thread #0, tick = 300000
Thread #0, tick = 350000
Thread #0, tick = 400000
Result description:
Thread 1 with a higher priority starts to run until it ends. Thread 0 with a lower priority starts to run.
Although thread 1 with a higher priority calls the yield method to discard CPU resources and allows Thread 0 to compete, it is immediately snatched back by thread 1, so there is no difference in the yield Method
If a sleep statement is added after the yield method, so that thread 1 temporarily stops running on the CPU, even if it is 1 millisecond, Thread 0 can also be scheduled. The modified run method is as follows:
Public void run () {while (tick <400000) {tick ++; if (tick % 50000) = 0) {// display System at intervals of 50000. out. println ("Thread #" + num + ", tick =" + tick); yield (); // discard execution permission try {sleep (1);} catch (Exception e) {}}}}
The running result is as follows:
Thread #1, tick = 50000
Thread #1, tick = 100000
Thread #1, tick = 150000
Thread #1, tick = 200000
Thread #0, tick = 50000
Thread #1, tick = 250000
Thread #1, tick = 300000
Thread #0, tick = 100000
Thread #1, tick = 350000
Thread #1, tick = 400000
Thread #0, tick = 150000
Thread #0, tick = 200000
Thread #0, tick = 250000
Thread #0, tick = 300000
Thread #0, tick = 350000
Thread #0, tick = 400000
Description
Thread 0 with lower priority also receives a part of execution before thread 1 is completed, but thread 1 still has a higher priority.
The Java Virtual Machine itself does not support a thread to snatch the execution right of another thread with the same priority being executed.
Generally, we insert the yield () statement in a thread. This method will temporarily stop running threads. This is a thread with the same priority and has the opportunity to get scheduling and start running, however, threads with lower priority will still be ignored and will not participate in scheduling.
You may also be interested in:
Java learning notes series:
Java Study Notes 14 -- multithreading programming basics 1
Java study note 13-reflection mechanism and dynamic proxy
Java study note 12 -- Exception Handling
Java study note 11-Summary
Java Study Notes 10-generic Summary
Java study notes 9-internal class Summary
Java study note 8-interface Summary
Java study notes 7 -- abstract classes and abstract methods
Java study Note 6-class inheritance, Object class
Java study notes 5-Class Method
Java study note 4-object initialization and collection
Java Study Notes 3-Basics of classes and objects
Java study Note 2 -- data type, array
Java study Note 1-Summary of the development environment Platform