gpt4 book ai didi

java - 当 main 方法中声明 2 个对象时,代码会同时编译吗?

转载 作者:行者123 更新时间:2023-12-01 22:43:30 24 4
gpt4 key购买 nike

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

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

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

最佳答案

This is because you are using multi threading and multi threading provides parallel execution.

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

另外,由于CPU使用了线程调度算法(Round Robin等),所以会发生切换。

关于java - 当 main 方法中声明 2 个对象时,代码会同时编译吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58482376/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com