有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

多线程Java可运行接口解决方案

有人能解释一下下面的代码吗

public class TestThread implements Runnable {

    public static void main(String[] args) {
        Thread thread = new Thread(new TestThread());
        thread.start();
        System.out.println("1");
        thread.run();
        System.out.println("2");

    }

    @Override
    public void run() {
        System.out.println("3");
    }
}

输出结果为1 3 2。谁能解释一下吗

提前谢谢


共 (1) 个答案

  1. # 1 楼答案

    当你调用线程时。start()方法,则run()方法中的代码将在新线程上执行(因为TestThread类实现Runnable)

    当你调用线程时。run(),这是从主线程中调用run()方法,而不是之前启动的方法。这基本上不使用任何线程功能

    一旦这个run()函数从主线程完成,它就会退出这个函数并到达println(“2”)行

    这似乎很直观,因为你调用了线程。在println(“1”)之前,start()表示它应该打印“3 1 3 2”,但是,由于多线程的复杂性,无法保证以实现这种方式进行任何排序。根据许多因素,它可以打印“1 3 2”或“3 1 3 2”

    你可以尝试的一个实验是让print语句包含调用它们的线程的名称

    public class TestThread implements Runnable {
    
        public static void main(String[] args) {
            Thread thread = new Thread(new TestThread(), "newThread");
            thread.start();
            System.out.println(Thread.currentThread().getName() + ": 1");
            thread.run();
            System.out.println(Thread.currentThread().getName() + ": 2");
        }
    
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + ": 3");
        }
    }
    

    对我来说,这意味着:

    main: 1
    main: 3
    newThread: 3
    main: 2