簡體   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