播放JMF视频时更新视频控制UI时出现Java并发问题



我正在围绕JMF用纯Java构建一个视频播放器,带有完全自定义的UI控件。一切都很好,直到我放入一个JLabel,它以hh:mm:ss.ss格式更新当前播放时间。标签更新是可以接受的,但偶尔会一次暂停10秒以上,这是不可接受的。

JMF Player是在SwingUtilities.invokeLater(new Runnable()...块中创建的。这是UI更新代码:

protected void createUIUpdater() {
    System.out.println("Creating UI updating worker thread");
    new Thread() {
        @Override
        public void run() {
            while(mediaPlayer.getState() == Controller.Started) {
                updatePlayPosition();
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    System.err.println("Sleep interrupted!");
                }
            }
            System.out.println("UI Updater thread finished.");
        }
    }.start();
}
protected void updatePlayPosition() {
    Movie movie = timelineEditor.getMovie();
    movie.setInsertionPoint(Rational.valueOf(mediaPlayer.getMediaTime().getSeconds()));
    updateTimeLabel();
}
protected void updateTimeLabel() {
    Movie movie = timelineEditor.getMovie();
    Rational time = movie == null ? new Rational(0,1) : movie.getInsertionPoint();
    // ... hours/minutes/seconds calculated
    timeLabel.setText((hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes)
            + ":" + (seconds < 10 ? "0" + seconds : seconds)
            + "." + (frame < 10 ? "0" + frame : frame));
}

其在CCD_ 4上的CCD_。在此期间,正在播放音频/视频。

诚然,在Java中处理并发时,我还是个新手,我相信有更好的方法来处理这个单独的线程。有什么建议吗?

您可以用ScheduledExecutiorService替换Thread/sleep:http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/ScheduledExecutorService.html

因为在使用sleep时,无法保证线程实际睡眠的时间,因此可能需要更长的时间才能返回到运行状态。

经过仔细检查,我的线程似乎执行得很好,只是偶尔在mediaPlayer.getMediaTime()上被阻塞(其中mediaPlayerjavax.media.Player)。

事实证明,调用mediaPlayer.getMediaNanoseconds()不会阻塞。

最新更新