[英]Java thread life time
Suppose I have the following: 假设我有以下内容:
public class A
{
Thread t = new Thread(new Runnable() {
@Override
public void run() {
B b = new B();
}
});
}
class B{
// long running process and alot of code
}
The question is that all process and work that class B does goes under thread t or just when the object of class B is created and work of class B starts t is no more available? 问题是,类B所做的所有过程和工作都在线程t下进行,或者仅当类B的对象创建并且类B的工作开始于t时才可用?
The run()
method calls the B constructor and then returns. run()
方法调用B构造函数,然后返回。 So that's the only thing that happens in the spawned thread: the constructor of B is executed. 因此,这是在生成的线程中发生的唯一事情:B的构造函数被执行。 Having a long process running in a constructor is a serious design smell. 在构造函数中运行很长的过程是一种严重的设计气味。 Constructors are not meant to execute a long sequence of instructions. 构造函数无意执行较长的指令序列。 They're meant to construct an object. 它们旨在构造一个对象。
The code should better look like the followingg: 代码最好看起来像下面的g:
Thread t = new Thread(new Runnable() {
@Override
public void run() {
B b = new B();
b.doSomethingLong();
}
});
Also note that nothing will happen at all if you don't start the thread: 另请注意,如果不启动线程,则什么也不会发生:
t.start();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.