仅当当前没有其他线程处于打开状态时,才可以创建新线程吗? [英] How can I create a new thread only if no other threads are currently open?

查看:75
本文介绍了仅当当前没有其他线程处于打开状态时,才可以创建新线程吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码创建并启动线程:

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.

推荐答案

您可以创建ExecutorService,该ExecutorService仅允许使用

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

这篇关于仅当当前没有其他线程处于打开状态时,才可以创建新线程吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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