Java 未传递以下程序作为线程引用执行的方式
我无法理解下面这个程序的行为,我可以看到没有线程引用,我们可以在其中传递myThread引用,但程序仍在执行。请告知是主线程在执行这个程序吗Java 未传递以下程序作为线程引用执行的方式,java,multithreading,Java,Multithreading,我无法理解下面这个程序的行为,我可以看到没有线程引用,我们可以在其中传递myThread引用,但程序仍在执行。请告知是主线程在执行这个程序吗 class MyThread extends Thread { public static void main(String [] args) { MyThread t = new MyThread(); t.start(); System.out.print("one. ");
class MyThread extends Thread
{
public static void main(String [] args)
{
MyThread t = new MyThread();
t.start();
System.out.print("one. ");
System.out.print("two. ");
}
public void run()
{
System.out.print("Thread ");
}
}
输出是
one. two. Thread
该程序由两个线程组成
t.start();
…将启动第二个线程,该线程将运行MyThread类的
run
方法中的代码。因为当您调用t.start()
时,将执行run()
方法(您重写)
start()方法:
我总是发现让主类扩展某些东西(在示例代码中)的做法充其量是可疑的,因为初学者不清楚,当调用
Main
方法时,实际上还没有主类的实例(在本例中是MyThread类)
因此,我重写了这个示例,以便更清楚地了解发生了什么:
public class Main
{
public static void main(String [] args)
{
// main gets called when starting your program (which is a thread created by the JVM for free)
MyThread t = new MyThread(); // You create a new Thread here
t.start(); // You start the thread
System.out.print("one. "); // In the mean time, the main thread keeps running here
System.out.print("two. ");
}
public static class MyThread extends Thread {
@Override
public void run()
{
System.out.print("Thread ");
}
}
}
你应该加上一些停顿,因为这些语句太小(及时)。添加一个
线程。sleep(200)
在开始模拟进程之后,您将看到线程正在运行。但是操作系统在这里没有足够快地出手,所以主线程有时间结束。要了解更多信息,您应该完全按照预期阅读CPUEverything中线程的实际工作方式。主线程执行main
,创建线程t并启动它,然后输出一个线程。两个。线程t输出线程。当它被安排执行时,情况就不同了。但在一个监视器中(调试时),你会清楚地看到,有一个单独的线程正在执行。“我可以看到,没有线程引用,我们可以传递myThread引用,但程序仍在执行”——这是什么意思?请澄清你的问题。在任何情况下,MyThread
都是Thread
的一个子类,因此它是Thread
。您正在对其调用Thread.start()
方法。所以它执行。我不清楚您预期会发生什么不同的情况。您可以在输出中添加Thread.currentThread().getName()
,以检查它在哪个线程上执行。例如:System.out.print(“one.from”+Thread.currentThread().getName())
查看这篇文章以了解完整的工作流:请解释重写run
@AxelH的问题Thread类中的start()方法调用它的run()方法,因为MyThread扩展了Thread并重写了Thread的run()版本,所以会调用你的run()方法。因为不清楚OP到底不理解什么,我想说,这个答案如何有助于OP对线程的理解,目前还不清楚。除此之外,我没有看到OP问“为什么…”的问题,而这个问题可以用“因为…”开头的答案来回答@阿克塞尔他为什么要解释?我没有看到gaston在任何地方提到重写run
Ok有问题,我对这个问题的理解与大家不同。。。所以我在寻找代码中的问题。我不明白为什么重写运行
可能是OP代码中意外行为的原因。对我来说,OP理解线程,但不明白为什么他的输出不符合预期顺序(threadone-two
)。PS:我的评论是为了改进答案,我很清楚这是如何工作的。
public class Main
{
public static void main(String [] args)
{
// main gets called when starting your program (which is a thread created by the JVM for free)
MyThread t = new MyThread(); // You create a new Thread here
t.start(); // You start the thread
System.out.print("one. "); // In the mean time, the main thread keeps running here
System.out.print("two. ");
}
public static class MyThread extends Thread {
@Override
public void run()
{
System.out.print("Thread ");
}
}
}