我目前的问题是我需要能够随时了解基本播放器实例的状态。这将需要线程在扫描器等待来自用户的输入时获得状态。状态将用于自动播放下一个音频文件。我做过的事情。首先,我确保此代码内联工作。接下来我试着在线程中,无济于事。我认为这与在两个线程之间同步对象有关
我尝试制作基本播放器实例的同步getter,但它不起作用
public class Player implements Runnable {
private String song;
private boolean comp = false;
private String path;
private final BasicPlayer player;
public Player () {
player = new BasicPlayer();
path = System.getProperty("user.dir") +"/src/Music/";
}
public void setSongName (String songName) {
song = songName;
}
public String getSongName() {
return song;
}
public void play () {
try {
player.open(new URL("file:///" + path + song));
player.play();
new Thread(new Player()).start();
} catch (BasicPlayerException | MalformedURLException e) {
e.printStackTrace();
}
}
private synchronized boolean isComplete () {
return getStatus() == 2;
}
public synchronized int getStatus(){
synchronized (player) {
return getPlayer().getStatus();
}
}
public synchronized boolean getComplete() {
return comp;
}
public synchronized void setComp(boolean comp) {
this.comp = comp;
}
private synchronized BasicPlayer getPlayer() {
synchronized (player) {
return player;
}
}
@Override
public void run() {
while (!isComplete()) {
BackendUtils.sleep(1000);
System.out.println(getStatus());
setComp(false);
}
setComp(true);
}
}
在这段代码中,我试图更新一个同步的布尔值,然后知道音频已完成标记为comp。我尝试使用同步的播放器实例。以下代码演示了我如何测试线程是否有效。
import java.util.Scanner;
public class BackendTesting {
private static Scanner scanner = new Scanner(System.in);
private static Player player = new Player();
public static void main(String[] args) {
while (true) {
String input = input("$ ");
if (input.contains("ply play")) {
player.setSongName(input.substring(input.lastIndexOf(" ") + 1) + ".mp3");
player.play();
}
}
}
private static String input (String prompt) {
System.out.print(prompt);
return scanner.nextLine();
}
}
答案 0 :(得分:0)
尝试这样的事情:
在线程类
中public void run() {
MainClass.getInstance().playNextSong();
}
在主要班级
public void playNextSong(){
synchronized(lock)
{
while (!isComplete()) {
lock.wait();
}
setComp(true);
lock.notifyAll();
}
}
当然你必须根据你的需要更新它。
希望有所帮助。