java - 线程新手需要java方面的建议

标签 java swing concurrency

我正在编写一个音乐播放器。当我从外部音乐文件读取数据时,我用幅度信息填充缓冲区。因为我认为将这个阻塞操作生成到它自己的线程中是有意义的,所以我添加了一个在 runnable 中运行它的接口(interface):

public class AudioInterface implements Runnable {

 public void run() 
 {
    AudioManager am = new AudioManager();
    am.play("res/sample2.mp3");
 }
}

这是我的以下问题:

  • 如何从另一个类创建 Hook 来轮询幅度数据?我需要它来编写一个将绘制到 JPanel Canvas 上的算法。
  • 支持可视化的面板也应该位于不同的线程中吗?
  • 目前 run() 仅包括播放文件,由于只有一个运行操作,我将如何使用此线程执行其他操作,例如摆姿势和寻找等。

谢谢

最佳答案

一些想法:

How do I create a hook from another class to poll the amplitude data? I need it to write an algorithm that will be drawn onto a JPanel canvas.

由于这是一个 Swing 程序,请考虑使用 SwingWorker 作为后台线程,然后通过 SwingWorker 的发布/处理方法对将幅度数据泵送到程序的 GUI 部分。

Should the panel that enables visualization also be in a different thread?

这里要小心。所有 Swing 代码都应该在一个线程上调用,并且只能在一个线程(事件调度线程)上调用。请看一下这方面的教程,Concurrency in Swing .

Currently run() only includes playing the file, how would I use this thread for other actions such as posing and seeking etc.

为此,您不使用“线程”,而是调用对象的方法。

此外,您可能希望将 AudioManager 变量声明为类字段,而不是局部变量,因为否则它的范围仅限于声明它的方法,从而阻止其他代码与其交互。

关于java - 线程新手需要java方面的建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12993943/

相关文章:

java - 如何在 JTextArea swing 中实现 autosugesion

java - 如何垂直对齐 JLabel-JTextField 对

java - thanAccept() 不打印值

java - 追加字符串

java - 在构造函数中创建对象与在声明中创建对象之间的区别

C++/g++ : Concurrent program

java - 基本 Java 线程(4 个线程)比非线程慢

java - 在计算器应用程序上 toast 时出错

java - 字符串日期值转换

java - 构建Antlr时,Visual Studio在未命名文件的情况下给出错误 "cannot find the file specified"