【发布时间】: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