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

后端 未结 3 799
傲寒
傲寒 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:23

    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

提交回复
热议问题