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
1. To control the order of thread locks to remain consistent, you can use the flexible locks in the java.util.concurrent.locks package
2. Use the atomic classes of the java.util.concurrent.atomic package
The execution of the CPU is too fast. The first thread finished executing quickly. The second thread may not have been created yet. Try changing the value of the loop to 1000. You should be able to see the effect, but it will definitely not be the case. Crossed, it’s confusing
CPU execution tasks are executed out of order, and synchronization between multiple threads is not guaranteed. If you want to ensure the order, you need to perform synchronization control