Java 仅当当前没有其他线程打开时,如何创建新线程?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2077771/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I create a new thread only if no other threads are currently open?
提问by Illes Peter
This code creates and starts a thread:
此代码创建并启动一个线程:
new Thread() {
@Override
public void run() {
try { player.play(); }
catch ( Exception e ) { System.out.println(e); }
}
}.start();
I'd like to modify this code so that the thread only starts if there are no other threads open at the time! If there are I'd like to close them, and start this one.
我想修改此代码,以便该线程仅在当时没有其他线程打开时才启动!如果有,我想关闭它们,然后开始这个。
采纳答案by Kaleb Brasee
You can create an ExecutorService
that only allows a single thread with the Executors.newSingleThreadExecutor
method. Once you get the single thread executor, you can call execute
with a Runnable
parameter:
您可以创建一个ExecutorService
只允许使用该Executors.newSingleThreadExecutor
方法的单个线程。获得单线程执行器后,您可以execute
使用Runnable
参数进行调用:
Executor executor = Executors.newSingleThreadExecutor();
executor.execute(new Runnable() { public void run() { /* do something */ } });
回答by appusajeev
you could create a static data member for the class(where threading takes place) which is incremented each time an object of that class is called,read that and u get the number of threads started
您可以为类(线程发生的地方)创建一个静态数据成员,每次调用该类的对象时都会增加该成员,读取该成员并获得启动的线程数
回答by user3466773
My preferred method would be putting a synchronized keyword on the play method
我的首选方法是在 play 方法上放置一个 synchronized 关键字
synchronized play()
synchronized methods will lock the function so only one thread will be allowed to execute them at a time.
同步方法将锁定函数,因此一次只允许一个线程执行它们。
Here's some more info https://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html
这是更多信息 https://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html