簡體   English   中英

Java如何停止線程並發運行

[英]Java how to stop Threads running concurrently

每當嘗試使用按鈕從ActionEvent調用talk(String text,boolean voiceEnabled)方法時,我都會嘗試使文本到語音線程停止。

當按下這些按鈕時,不同的文本字符串將傳遞給該方法,該方法將在新線程上運行音頻。 如果當前線程仍在運行,但是發生新的ActionEvent,則我需要當前線程停止(例如,文本到語音),以便可以在不播放當前音頻片段和新片段的情況下播放新的文本到語音音頻在彼此的頂部。

這是我目前擁有的,但是TTS音頻在彼此的上方播放。 我需要當前的TTS在觸發新的TTS后立即停止。 我相信我的主要問題是每次調用該方法時都會創建一個新的線程。

任何幫助,不勝感激。 謝謝!

public void talk(String text, boolean voiceEnabled) {
    System.out.println(text);

    // Create a new Thread as JLayer is running on the current Thread and will
    // make the application lag
    Thread thread = new Thread(() -> {
        try {
            // Create a JLayer instance
            AdvancedPlayer player = new AdvancedPlayer(synthesizer.getMP3Data(text));
            if (voiceEnabled) {
                player.play(); //Plays the TTS audio
                System.out.println("Successfully retrieved synthesizer data");
            }
            else {
            }
        } catch (IOException | JavaLayerException e) {

            e.printStackTrace();
        }
    });
    // We don't want the application to terminate before this Thread terminates
    thread.setDaemon(false);
    // Start the Thread
    thread.start();
}

您似乎正在將關鍵引用隱藏在匿名內部類中,並且我看不到如何以及何時需要它們。 為什么這樣 為什么不創建一個非匿名類的實例,一個帶有AdvancedPlayer字段的實例,一個實例的引用由某個集合(也許是List<...>或HashMap)保存,或者如果只運行一到兩個,則由變量保存,您可以在其中提取對象,獲取其AdvancedPlayer字段並在其上調用.stop()

例如,

public class RunnablePlayer implements Runnable {
    private AdvancedPlayer player;
    private String text;
    private boolean voiceEnabled;

    public RunnablePlayer(String text, boolean voiceEnabled) {
        this.text = text;
        this.voiceEnabled = voiceEnabled;
    }

    @Override
    public void run() {
        try {
            // Create a JLayer instance
            player = new AdvancedPlayer(synthesizer.getMP3Data(text));
            if (voiceEnabled) {
                player.play(); //Plays the TTS audio
                System.out.println("Successfully retrieved synthesizer data");
            } 
        } catch (IOException | JavaLayerException e) {
            e.printStackTrace();
        }
    }

    public AdvancedPlayer getPlayer() {
        return player;
    }

    public void stop() {
        // perhaps do a null check here first?
        if (player != null) {
            player.stop();
        }
    }
}

然后,您可以擁有一個類的字段,例如:

// field of the class
private RunnablePlayer runnablePlayer;

並在您的交談方法中使用它:

public void talk(String text, boolean voiceEnabled) {
    if (runnablePlayer != null) {
        runnablePlayer.stop();  // not calling this on a Thread
    }

    runnablePlayer = new RunnablePlayer(text, voiceEnabled);
    Thread thread = new Thread(runnablePlayer);
    //.....
    thread.start();
}

代碼未經編譯或測試,只是為了給出總體思路而提出。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM