java - new了2个Thread,为什么不是交叉打印?
PHPz
PHPz 2017-04-18 10:27:18
0
13
1511
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 
PHPz
PHPz

学习是最好的投资!

reply all(13)
阿神

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template