class Hello {
public Thread create(int index){
return new Thread(
new Runnable() {
@Override
public void run() {
if(index == 1){
System.out.println("index=1");
}else{
System.out.println("hello");
}
}
}
);
}
public static void main(String[] args) {
Hello hello = new Hello();
Thread thread = hello.create(1);
thread.run();
}
}
结果上是可以运行的。
但我不太理解,Thread thread = hello.create(1);这一步得到的thread,内部难道是这样:
{
int index = 1;
...
}
的? 还是
{
Runnable target = { int index = 1; ....}
....
}
这样的?
就是从理论上来说作为create(int)的参数传入的index和它的值,应该在函数调用结束后便销毁,但实际上new出来的thread记录了这个值,它是怎么记录的?有相关的官方文档来说明这一情况下的规则么?
另外,如果这里使用 java8 的 lambda 来写,其记录时的行为一样么?
谢谢