Only one thread at a time!

2019-02-12 04:18发布

Here's my code:

new Thread() {
    @Override
    public void run() {
        try { player.play(); }
        catch ( Exception e ) { System.out.println(e); }
    }
}.start();

which creates and starts a thread. 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. Thanks in advance!

3条回答
手持菜刀,她持情操
2楼-- · 2019-02-12 04:45

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

查看更多
Bombasti
3楼-- · 2019-02-12 04:50

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 */ } });
查看更多
霸刀☆藐视天下
4楼-- · 2019-02-12 04:59

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

查看更多
登录 后发表回答