How can I create a new thread only if no other threads are currently open?

后端 未结 3 803
傲寒
傲寒 2021-01-01 19:40

This code creates and starts a thread:

new Thread() {
    @Override
    public void run() {
        try { player.play(); }
        catch ( Exception e ) { Sy         


        
3条回答
  •  礼貌的吻别
    2021-01-01 20:33

    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 */ } });
    

提交回复
热议问题