Java 在 class 中创建的线程中使用此关键字

Java using this keyword inside a thread created inside a class

我有一些这样的代码:

class MyClass{
    final ArrayList<Thread> list= new ArrayList<>();
    for(int i=0;i<N;i++)
        new Thread(()->{
            //more instructions...
            list.remove(this);
        }).start();
}

问题是关于 IntelliJ 对指令 list.remove(list); 显示的警告告诉我:ArrayList<Thread> may not contains objects of type MyClass

是 IntelliJ 的错误分析,还是我的场景中的 this 关键字引用了封闭的 class MyClass

this 指的是 MyClass 实例。

那是因为您使用的是 lambda 表达式,它本身没有 this 上下文。

但即使你用匿名子类替换了 lambda 表达式,像这样:

new Thread(new Runnable() {
    public void run() {
        list.remove (this);
    }
})

那么 this 将引用 Runnable 的匿名子类,而不是 Thread 实例。

this关键字指的是调用该方法的对象。在本例中为 MyClass。您的列表包含线程。您的代码试图从包含线程的列表中删除此对象 (myclass)。

这没有意义

我找到了适合我需要的解决方法:

class MyClass{
final ArrayList<Runnable> list= new ArrayList<>();
for(int i=0;i<N;i++)
    new Thread(new Runnable() {
    @Override
    public void run() {
        //more instructions...
        list.remove(this);
    }
}).start();

我更改了列表,使其包含 Runnable 个对象,然后 this 将引用 Runnable class。

您可以使用 Runnable 来避免 this 关键字冲突。

改用 Runnable 将帮助您避免包装上下文。