search

Home  >  Q&A  >  body text

java - new了2个Thread,为什么不是交叉打印?

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 
PHPzPHPz2884 days ago1579

reply all(13)I'll reply

  • 阿神

    阿神2017-04-18 10:29:18

    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

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-18 10:29:18

    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

    reply
    0
  • 高洛峰

    高洛峰2017-04-18 10:29:18

    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

    reply
    0
  • Cancelreply