Then in the previous section, we introduce the attention points of multithreading in this section.
The order and time of execution between threads are different
Let's change the code in the previous section:
Package Com.ray.ch17;public class Test {public static void main (string[] args) {for (int i = 5; i < 8; i++) {Donemissio n donemission = new donemission (i); Thread thread = new Thread (donemission); Thread.Start ();} System.out.println ("Working");}} Class Donemission implements Runnable {private final int id = index++;p rivate int count = 0;private static int index = 0;p Ublic donemission (int count) {This.count = count;} Public String leftmission () {return "#" + ID + "(" + Count + ")";} @Overridepublic void Run () {while (count--> 0) {System.out.print (leftmission ()); Thread.yield ();}}}
Output:
Working
#0 (4) #2 (6) #1 (5) #2 (5) #2 (4) #2 (3) #2 (2) #2 (1) #1 (4) #1 (3) #1 (2) #2 (0) #1 (1) #1 (0) #0 (3) #0 (2)
From the output you can see that the thread of the main method and the thread that we started do not follow the established order in the execution.
If we run a few more times, we can also see that the order of the results of the subsequent runs is not the same:
Working
#2 (6) #0 (4) #0 (3) #0 (2) #0 (1) #0 (0) #2 (5) #1 (5) #2 (4) #1 (4) #2 (3) #1 (3) #1 (2) #2 (2) #2 (1) #1 (1)
Working
#1 (5) #1 (4) #1 (3) #1 (2) #1 (1) #1 (0) #2 (6) #2 (5) #2 (4) #2 (3) #2 (2) #0 (4) #0 (3) #0 (2) #0 (1) #2 (1)
Summary: This chapter focuses on the issue of the order of execution between threads.
This chapter is here, thank you.
-----------------------------------
Directory
Understanding java-17.2 Basic threading mechanism from the beginning (1)-First knowledge multithreading-2