有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

多线程如果一个方法属于扩展线程的另一个类,但从主线程调用,它是由主线程还是子线程执行?(爪哇)

我知道有一些类似的问题,但我找不到一个具体的答案来回答这个问题——如果我错了,请道歉,确实有。我会通过考试的。toString()方法是由主线程执行,还是由调用它之前启动的测试线程执行?我们中的一些人正在为复习考试而争论这个问题,我很好奇答案是什么

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
   }
}

共 (2) 个答案

  1. # 1 楼答案

    调用总是在调用线程上执行。大量的代码都是基于此的——例如spring框架的整个安全性和事务基础设施

    这一事实很容易证明:

    public class Main {
        static ThreadLocal<String> threadContext = new ThreadLocal<String>();
    
        public static void main(String[] args) throws InterruptedException {
            threadContext.set("Main");
            TestThread test = new TestThread();
            new Thread(test).start();
            System.out.println("Main: " + test.getContext());
        }
    
        static class TestThread implements Runnable {
            @Override
            public void run() {
                threadContext.set("ThreadTest");
                System.out.println("TestThread: " + getContext());
            }
    
            String getContext() {
                return threadContext.get();
            }
        }
    }
    

    正如@davidermann已经说过的:您应该实现Runnable,而不是扩展Thread

  2. # 2 楼答案

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

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

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

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

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

    Test: x = 3 executed on thread 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
           }
    }