我有一些这样的代码:
class MyClass{
final ArrayList<Thread> list= new ArrayList<>();
for(int i=0;i<N;i++)
new Thread(()->{
//more instructions...
list.remove(this);
}).start();
}
Run Code Online (Sandbox Code Playgroud)
问题是关于 IntelliJ 为指示list.remove(list);我显示的警告:ArrayList<Thread> may not contains objects of type MyClass
是 IntelliJ 的错误分析,还是this我的场景中的关键字引用了封闭类MyClass?
this指MyClass实例。
那是因为您使用的是 lambda 表达式,this它本身没有上下文。
但即使你用匿名子类替换了 lambda 表达式,如下所示:
new Thread(new Runnable() {
public void run() {
list.remove (this);
}
})
Run Code Online (Sandbox Code Playgroud)
然后this将引用 的匿名子类Runnable,而不是Thread实例。
| 归档时间: |
|
| 查看次数: |
267 次 |
| 最近记录: |