Java – allocate memory using thread

I wonder what happens if a local thread is declared in a method? Usually, after the function returns, all local variables disappear because they are allocated on the stack However, it seems that local threads will be a different story Is that right?

public int A() {
    Thread t = new Thread() {
        doSomething();
    }
    t.start();
    return -1;
 }

Solution

A thread is its own GC root Therefore, whenever a thread is created, regardless of its creation context, it will not be ready for GC until its running method is completed This is true even if the local method completes and the thread is still active

Example:

public void doSomeAsync(){
   Thread th = new Thread(new Runnable(){
      public void run(){
          Thread.sleep(500);
      }
   });
   th.start();
   //do something else quickly
}

//After some other quick action, mark any undefined method as GC Threads th will not be marked as GC and will be correctly placed on the heap with its own thread stack

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>