简体   繁体   English

中断后线程的对象变量仍然可用

[英]Object variables still available of a thread after interrupting

i have this thread 我有这个线程

public class ThreadA extends Thread {

private final String lala = "lala";

@Override
public void run() {
    Scanner scanner = new Scanner(System.in);
    String value = scanner.next();
    while (!value.equals("stop") && !isInterrupted()) {
        value = scanner.next();
    }
    interrupt();
    System.out.println("exit");
}

public String getMe() {
    return lala;
}

} }

and I wonder why I always can access to the method getMe() even when the Thread is already interrupted. 我不知道为什么即使线程已经中断,我也总是可以访问方法getMe()。

Why is that so? 为什么会这样? And is that always possible, even after days or will the Garbage Collector somewhen delete that object? 而且即使在几天之后,这是否总是可能的呢?还是在删除该对象时垃圾回收器会删除该对象?

interrupt() just sets a special flag. interrupt()只是设置一个特殊标志。 In you case it doesn't do anything special. 在您的情况下,它并没有做任何特别的事情。

I wonder why I always can access to the method getMe() even when the Thread is already interrupted. 我不知道为什么即使线程已经中断,我也总是可以访问方法getMe()。

To do this you must have a reference to the ThreadA object and while you hold that reference you will always be able to call it. 为此,您必须具有对ThreadA对象的引用,并且在拥有该引用的同时,您始终可以对其进行调用。

is that always possible, even after days or will the Garbage Collector somewhen delete that object 哪怕是几天之后,这是否总是可能的?或者垃圾回收器在删除该对象时是否会

Yes, when the thread is not running, it is just a plain object like any other and it will exist as long as you hold a reference to it. 是的,当线程未运行时,它只是一个普通对象,就像其他线程一样,只要您持有对该对象的引用,它就会存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM