我看到这样的评论
我发现这个问题的一个地方是你继续创建线程,而不是调用start( ),直接在线程对象上调用run()。 这将导致线程对象无法解除引用... 因此在一段时间后无法创建新的本机线程的消息出现
one place i have seen this problem is if you keep creating threads, and instead of calling start(), call run() directly on the thread object. This will result in the thread object not getting dereferenced... So after sometime the message unable to create new native thread comes up
Sun Java论坛上的
on the Sun Java Forums
在我的应用程序中,我们最初计划使用线程,但后来我们决定不再需要了,所以我们只调用run()而不是start()。我们是否需要为新的threadClass(..)做手动GC?
In my application, initialy we plan to use thread, but later, we decided no need anymore, so we just call run() instead of start(). Do we need to do manual GC for new threadClass(..) ?
我的tomcat启动设置
my tomcat startup setting
-Xms1024m -Xmx1024m -XX:MaxPermSize=450m推荐答案
为什么首先要创建一个 Thread ?
Why do you create a Thread in the first place?
你的代码应该实现 Runnable interface。
Your code should implement the Runnable interface instead.
然后,当你决定要在一个线程中运行它时,简单地实例化一个 Thread 使用 Runnable 作为参数,并在线程对象。
Then, when you decide that you want to run it in a thread, simple instantiate a Thread with the Runnable as the argument and call start() on the Thread object.
如果您只想在当前线程中运行它,只需调用运行你的 Runnable 对象上的()。
If, instead, you just want to run it in your current thread, simply call run() on your Runnable object.
这有几个好处:
- 您不需要任何 Thread 对象。因为你不关心单独的线程
- 你的代码被包装在 Runnable 中,这在概念上更接近:你不是在写一些特殊的线程,你呢?您只需编写一些可以执行/运行的代码。
- 您可以轻松切换到使用 执行者 进一步抽象决定
- you don't involve any Thread objects as long as you don't care about separate threads
- your code is wrapped in a Runnable which fits closer conceptually: you're not writing some special kind of Thread, do you? You simply write some code that can be executed/run.
- you can easily switch to using an Executor which further abstract away the decision
最后但并非最不重要的是,你避免了对是否创建本机线程资源的任何混淆。
And last but not least you avoid any potential confusion on whether or not a native thread resource is created.
更多推荐
java.lang.OutOfMemoryError:无法创建新的本机线程
发布评论