First understanding of java-17.2 basic thread mechanism (1)-First understanding of multithreading-2
Next, let's take a look at the attention of multithreading in the previous chapter.
The execution sequence and time between threads are different.
Let's modify the code in the previous chapter:
package com.ray.ch17;public class Test {public static void main(String[] args) {for (int i = 5; i < 8; i++) {DoneMission doneMission = new DoneMission(i);Thread thread = new Thread(doneMission);thread.start();}System.out.println("working");}}class DoneMission implements Runnable {private final int id = index++;private int count = 0;private static int index = 0;public 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) #0 (1) #0 (0)
From the output, we can see that the thread of the main method and the thread we started do not follow the set sequence for execution.
If we run it several more times, we can also see that the subsequent running results are in different order:
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) #2 (0) #1 (0)
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) #2 (0) #0 (0)
Summary: This section describes the execution sequence between threads.