当java线程完成后,它们被删除 [英] Do java threads get deleted when they finish

查看:153
本文介绍了当java线程完成后,它们被删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我使用下面的方法每隔几秒产生一个线程,每个线程需要一秒钟来完成。完成的线程被删除?

  new Thread(new myRunnableClass())。 


解决方案

当线程结束时(大约 run()完成),但是线程对象像任何其他对象一样生存,直到它变得不可达,垃圾回收器感觉像运行。 / p>

编辑 Thread Sun的 Oracle的实现,任何人)有一个私有方法,当线程退出时,由VM调用,其中积极的几个字段,包括指向 Runnable 通过 Thread(Runnable)构造函数。因此,即使你保留对 Thread 的引用,在完成执行后它不需要的东西也会被释放。


Say I spawn a thread every couple seconds using the method below and every thread takes about a second to complete. Do the finished threads get deleted?

new Thread (new myRunnableClass()).start();

解决方案

The native, OS-level thread is released as soon as the thread finishes (circa when run() finishes), but the thread object lives, like any other object, until it becomes unreachable and the garbage collector feels like running.

Edit: It might also be interesting to know that Thread (in Sun's Oracle's implementation, anywho) has a private method called by the VM when the thread exits, which aggressively nulls several fields, including the one referring to the Runnable set by the Thread(Runnable) constructor. So even if you retain a reference to the Thread, the things it doesn't need after finishing execution will be released, regardless.

这篇关于当java线程完成后,它们被删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆