How can I create a new thread only if no other threads are currently open?
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:
Executor executor = Executors.newSingleThreadExecutor();
executor.execute(new Runnable() { public void run() { /* do something */ } });
My preferred method would be putting a synchronized keyword on the play method
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