如果一个方法属于另一个继承了

如果一个方法属于另一个继承了

本文介绍了如果一个方法属于另一个继承了 Thread 的类,但从主线程调用,它会被主线程还是子线程执行?(爪哇)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道那里有一些类似的问题,但我找不到专门回答这个问题的人 - 如果我错了,请道歉,而且确实有.test.toString() 方法是由主线程执行还是由我在调用它之前启动的测试线程执行?我们一群人正在为测试修订而争论这个问题,我很好奇答案是什么.

I know there are some similar questions out there, but I couldn't find one specifically answering this question - apologies if I was wrong, and there is. Would the test.toString() method be executed by the main thread, or the test thread that I started prior to it being called? A group of us are arguing about this for test revision and I am curious to what the answer is.

public class Main {
   public static void main(String[] args) {
       test = new ThreadTest("Test", 3);
       test.start();
       System.out.println(test.toString());
   }
}
public class ThreadTest extends Thread {
   public ThreadTest(String n, int x) {
       setName(n);
   }
   @Override
   public String toString() {
       return(getName() + ": x = " + x);
   }
   public void run() {
       //Nothing of any relevance to the problem occurs here
   }
}

推荐答案

toString() 调用在主线程上执行.主线程正在调用 Main.main();main() 直接调用test.toString().

The toString() call is executed on the main thread. The main thread is invoking Main.main(); main() directly invokes test.toString().

仅仅因为您的输出打印字符串Test"并不意味着这是执行它的线程.Thread 有状态;setName(...) 设置该状态(并且您的类 TestThreadTest 的子类,因此它也继承了这一点).在您的 toString() 实现中,您只是在打印该状态……而不是正在执行的线程的实际名称.

Just because your output prints the string "Test" doesn't mean that's the thread that is executing it. Thread has state; setName(...) sets that state (and your class TestThread is a subclass of Test so it inherits this as well). In your toString() implementation you're just printing that state... not the actual name of the executing thread.

为了证明这一点,请更改您的 TestThread.toString() 方法以同时打印当前正在执行的线程的名称并重新运行:

To prove this, change your TestThread.toString() method to also print the name of the currently executing thread and re-run:

   @Override
   public String toString() {
       return(getName() + ": x = " + x + " executed on thread " + Thread.currentThread().getName());
   }

您将看到以下打印到标准输出:

You will see the following print to standard out:

测试:x = 3 在线程 main 上执行

完整代码:

public class Main {
       public static void main(String[] args) {
           ThreadTest test = new ThreadTest("Test", 3);
           test.start();
           System.out.println(test.toString());
       }


}

public class ThreadTest extends Thread {
    private int x;
       public ThreadTest(String n, int x) {
           setName(n);
           this.x = x;

       }
       @Override
       public String toString() {
           return(getName() + ": x = " + x + " executed on thread " + Thread.currentThread().getName());
       }
       public void run() {
           //Nothing of any relevance to the problem occurs here
       }
}

这篇关于如果一个方法属于另一个继承了 Thread 的类,但从主线程调用,它会被主线程还是子线程执行?(爪哇)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 17:30