我正在测试一个重载视频,它加载视频并在Thread.sleep(1000)之后;它播放第二个视频。但是,一旦我在循环中一个接一个地播放,它就会冻结。
当我删除所有那些Thread.sleep(1000);它完美无缺地工作。
但我需要延迟(但不使用Thread.sleep方法),我们该怎么做呢?
package test;
public class Test
{
static String what = "0";
public static void main(String args[])
{
Load.video720p("/tmp/START.mp4"); // This is 8 second movie playing
new javax.swing.Timer(8000, new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
if (what.equals("0") )
{
/* After 8 seconds play 0.mp4 */
callMe();
what = "1";
} else {
/* After 8 seconds play 1.mp4 */
callMe();
what = "0";
}
}
}).start(); /* Keep on looping every 8 seconds. */
}
/* 8 seconds interval call me. */
public static void callMe()
{
try {
/* Try 0: Freeze/Do not play */
Load.video720p("/tmp/" + what + ".mp4");
/* Try 1: Does not change films (cant run)
new Thread(new Runnable() {
public void run() {
Load.video720p("/tmp/" + what + ".mp4", EVENT_TRIGGER_TRUE);
}
});*/
/* Try 2: Fails
try {
javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
Load.video720p("/tmp/" + what + ".mp4");
}
});
} catch (Exception e) {
System.err.println(e);
}*/
/* Try 3: Failes
try {
java.awt.EventQueue.invokeAndWait(new Runnable() {
public void run() {
Load.video720p("/tmp/" + what + ".mp4");
}
});
} catch (Exception e) {
System.err.println(e);
}*/
} catch (Exception e) {
System.out.println(e);
}
}
}
答案 0 :(得分:5)
如果您在事件处理线程上调用sleep()
,那么是,您的GUI将在此期间冻结。更好的办法是使用SwingTimer
,这样您就可以在指定的延迟后触发播放第二个视频而无需调用sleep()
。
答案 1 :(得分:1)
如上所述,SwingTimer是一个很好的解决方案
如果你想要它稍微复杂但是自制的启动一个新的线程来处理睡眠和新的负载。但我也更喜欢SwingTimer