【问题标题】:When there is 2 object being declared in main method, the code is being compiled simultaneously?当 main 方法中声明了 2 个对象时,代码正在同时编译?
【发布时间】:2020-02-17 07:28:45
【问题描述】:

我在这里研究多线程操作。但我目前对主要方法执行顺序感到怀疑。请向我解释这些,问题在下面标记。

这是我正在研究的一个简单程序

public class HelloWorld implements Runnable  {
    private Thread t;
    private String threadname;

    HelloWorld(String name){
        threadname= name;
        System.out.println("Create " +threadname);
    }

    public void run() {
        System.out.println("Running " +threadname);
        try {
            for(int i=4; i>0;i--) {
                System.out.println("Thread" +threadname +", "+i);
                Thread.sleep(50);
            }
        }catch(InterruptedException e) {
            System.out.println("Thread" +threadname +"interrupted ");
        }
        System.out.println("Thread" +threadname +"exiting ");
    }

    public void start() {
        System.out.println("Starting " +threadname);
        if(t==null)
        {
            t=new Thread(this, threadname);
            t.start();
        }
    }

    public static void main(String[] args) {
        HelloWorld obj1= new HelloWorld ("Thread-1");
        obj1.start();

        HelloWorld obj2= new HelloWorld ("Thread-2");
        obj2.start();
    }
}

实际结果

Create Thread-1
Starting Thread-1
Create Thread-2
Starting Thread-2
Running Thread-1
ThreadThread-1, 4
Running Thread-2
ThreadThread-2, 4
ThreadThread-2, 3
ThreadThread-1, 3
ThreadThread-1, 2
ThreadThread-2, 2
ThreadThread-1, 1
ThreadThread-2, 1
ThreadThread-2exiting 
ThreadThread-1exiting 

我的问题:

Create Thread-1
Starting Thread-1
Create Thread-2(why here will switch from 1 to 2)
Starting Thread-2
Running Thread-1
ThreadThread-1, 4
Running Thread-2(At here, I understand the thread is switch when Thread.sleep(50) is being executed;)
ThreadThread-2, 4
ThreadThread-2, 3
ThreadThread-1, 3
ThreadThread-1, 2
ThreadThread-2, 2
ThreadThread-1, 1
ThreadThread-2, 1
ThreadThread-2exiting 
ThreadThread-1exiting 

问:为什么这里会从1切换到2? main 方法中的 2 个对象是否同时运行?

【问题讨论】:

  • 主方法中的 2 个对象是否同时运行 - 是的,这是 Threads 的目的
  • @ScaryWombat 那么编译器如何知道它是线程,因为在 main 方法中,当编译器第一次运行 obj1 时,没有提到线程对象
  • HelloWorld
  • Re," 那么编译器如何知道它是线程...?"编译器对线程一无所知。它只知道函数调用。您的代码在执行t = new Thread(...) 时调用Java 标准库,然后调用t.start()。当start() 方法要求操作系统创建一个新线程时,真正的魔法发生了。

标签: java multithreading main


【解决方案1】:

这是因为你使用的是多线程和多线程 提供并行执行。

在 main 方法中,您启动了两个子线程 obj1.start() 和 obj2.start()。直到 obj1.start() 只有一个子线程(主线程是父线程)。但是当您启动第二个子线程 obj2.start() 时,现在有两个子线程正在并行执行,这就是发生切换的原因。两个线程将有单独的执行路径并并行运行。

此外,由于 CPU 使用了线程调度算法(轮询等),因此正在发生切换。

【讨论】:

    猜你喜欢
    • 2011-04-01
    • 2020-12-17
    • 1970-01-01
    • 1970-01-01
    • 2019-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-16
    相关资源
    最近更新 更多