[英]Why the execution thread for inner class, which extends thread, is the main thread?
I am having difficulty understanding the behavior of inner class threads. 我很难理解内部类线程的行为。
I have this simple test program. 我有这个简单的测试程序。
public class Test {
private static Random rand = new Random(System.currentTimeMillis());
public class TestThread extends Thread {
@Override
public void start() {
System.out.println("in start " + Thread.currentThread().getName());
try {
Thread.sleep(rand.nextInt(5000));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args){
System.out.println(Thread.currentThread().getName());
for(int i = 0; i < 5; ++i){
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(rand.nextInt(5000));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
}
}).start();
}
System.out.println("new run");
Test test = new Test();
for(int i = 0; i < 5; ++i){
(test. new TestThread()).start();
}
}
}
When the first for loop runs, the threads behaves as I expected. 当第一个for循环运行时,线程的行为符合我的预期。 Total of 6 threads, main, thread-0, thread-1, thread-2, thread-3, and thread-4.
共有6个线程,主线程,线程0,线程1,线程2,线程3和线程4。 Thread 0 - 4 are printed out of order as I expected.
线程0-4的打印顺序不正确。
The result for second for loop has me confused. 第二个for循环的结果让我感到困惑。
system.out.println("in start " + Thread.currentThread().getName());
It always prints out "main," and the threads are executed sequentially. 它总是打印出“ main”,并且线程是顺序执行的。 Why is the execution of the inner class thread carried out by the main thread?
为什么内部类线程的执行由主线程执行?
Thanks! 谢谢!
Don't override Thread.start()
. 不要重写
Thread.start()
。 The start method is always called from the thread that is starting it. 始终从启动它的线程中调用start方法。 You need to override
Thread.run()
. 您需要重写
Thread.run()
。
(See examples in the Thread
class' javadoc documentation ) (请参见
Thread
类的javadoc文档中的示例)
You shouldn't @Override
the start()
method. 您不应该
@Override
start()
方法。 You should @Override
run()
instead. 您应该改为
@Override
run()
。 Then call start()
. 然后调用
start()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.