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

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.

伊谢尔伦

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.

迷茫

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.

小葫芦

It’s too fast to output 10 numbers. Try changing 10 to 100.

黄舟

Add a thread sleep time

伊谢尔伦

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

Ty80

Add Thread.sleep(1000) before the output statements in the two for loops;
Try again

阿神

Threads do not guarantee the order of execution.

左手右手慢动作

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.

迷茫
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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!