我知道那里有一些类似的问题,但我找不到专门回答这个问题的人 - 如果我错了就道歉,并且有。 test.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
}
}
答案 0 :(得分: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();
}
}
}
正如@DavidEhrmann已经说过:你应该实施Runnable
而不是扩展Thread
。
答案 1 :(得分:0)
toString()
调用在主线程上执行。主线程正在调用Main.main()
; main()
直接调用test.toString()
。
仅仅因为您的输出打印字符串“Test”并不意味着执行它的线程。 Thread
有州; setName(...)
设置了该状态(并且您的类TestThread
是Test
的子类,因此它也继承了它。在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
}
}