有关Java多线程的问题

public class MyThread extends Thread {
    //在类中重写 run 方法,设置线程任务
    @Override
    public void run() {
        for(int j=0; j<20; ++j) {
            System.out.println("run:" + j);
        }
    }
}
public class Main {
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.run();

        for(int j=0; j<20; ++j) {
            System.out.println("main:" + j );
        }
    }
}

=================================

有关上面一段代码,一个视频教程中跑出了如下结果:

main: 0

run: 0

main:1

run:1

main:2

run:2

....

觉得有可能么?我在本机上测试了许多遍,都是输出完一个循环再输出另一个循环,完全没有交错输出

刚刚解答了这个相关的问题 你可以看一下https://ask.csdn.net/questions/7423954  原因就是 线程的启动不等于在运行,只能说进入了就绪状态,线程是要排序等待的。所以先后顺序不定。线程之间抢占CPU资源

你把代码改一下

public class Main {
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start();

        for(int j=0; j<20; ++j) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("main:" + j );
        }
    }
}
public class MyThread extends Thread {
    //在类中重写 run 方法,设置线程任务
    @Override
    public void run() {
        for(int j=0; j<20; ++j) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("run:" + j);
        }
    }
}

 

注意这句代码 thread.run();

thread.run(); 相当于直接在主线程调用run方法,和线程无关。

这里要调用Thread的start()方法,才是启动线程,以多线程的方式运行

线程之间会进行抢占式的运行,start后表明这个线程可以去抢占运行了,可能他连续抢到几次,也可能他连续几次都没抢到

你代码写错了,应该是:

    thread.start();

而不是

    thread.run();