繁体   English   中英

当main方法中声明了2个object时,代码是同时编译的吗?

[英]When there is 2 object being declared in main method, the code is being compiled simultaneously?

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

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

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 个对象是否同时运行?

这是因为您使用的是多线程,而多线程提供了并行执行。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM