public static void main(String[] args){
new Thread(new Runnable() {
@Override
public void run() {
for (int i=0; i<10; i++){
System.out.print(i+" ");
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
for (int i=0; i<10; i++){
System.out.print(i+" ");
}
}
}).start();
}
输出结果如下:
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9
阿神2017-04-18 10:29:18
The execution speed of the CPU is too fast, and the numbers are too small to see the difference. If it were me, at least Integer.MaxValue
.
伊谢尔伦2017-04-18 10:29:18
If there is no synchronization lock, the two threads will not have the cross-printing you mentioned. The priority of thread execution depends on who obtains the CPU resources first. Your program cannot guarantee which thread executes first. Let’s take a closer look at Java multi-threading knowledge.
迷茫2017-04-18 10:29:18
The number of settings is too small. If you set 100 numbers, you can see the printing effect of two threads crossing (the crossing here is not that thread 1 prints a number and thread 2 prints a number immediately, but segment by segment); cpu Execute as soon as you grab the resources. If you want to implement cross-printing, it is an example of production and consumer.
伊谢尔伦2017-04-18 10:29:18
0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 Mine is like this! Think about it for yourself
PHP中文网2017-04-18 10:29:18
Add Thread.sleep(1000) before the output statements in the two for loops;
Try again
ringa_lee2017-04-18 10:29:18
The execution order of threads is uncertain. Whoever seizes the CPU will execute it. The order of the ten numbers is not necessarily yours. If you execute it a few times, different results will appear. Moreover, the priority of the thread cannot guarantee the execution order of the thread. It's just that threads with higher priority have a higher probability of obtaining CPU resources.
迷茫2017-04-18 10:29:18
public void run() {
for (int i=0; i<10; i++){
System.out.print(i+" ");
Sleep(1000);
}
}
In this way, you can see a relatively obvious cross-printing phenomenon, but in fact, concurrency means that we cannot know which thread executes first and which thread
executes later, and it does not necessarily mean that there will be crossover. To exaggerate, by inserting m, n assembly instructions of two threads, there can be an execution sequence with multiple factorial levels.