本文介绍了有没有更好的或替代的方法来跳过/避免在 Java 中使用 Thread.sleep(1000)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在测试一个重载视频,它在 Thread.sleep(1000) 之后加载视频;它播放第二个视频.但是一旦我一个接一个地循环播放它就会冻结.

I was testing a heavy loaded video, which loads the video and after Thread.sleep(1000); it plays second video. But once i play one after another in loop it freeze.

当我删除所有这些 Thread.sleep(1000);它在没有冻结的情况下完美运行.

When i removed all those Thread.sleep(1000); it worked perfectly without freeze.

但我需要延迟(但不使用 Thread.sleep 方法),我们该怎么做?

But i need to make a delay (but not using Thread.sleep method), how can we do this?

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);
      } 
    }
} 

推荐答案

如果您在事件处理线程上调用 sleep() ,那么是的,您的 GUI 在此期间会冻结.一个更好的主意是使用 SwingTimer 这将允许您可以在指定延迟后触发播放第二个视频,而无需调用 sleep().

If you're calling sleep() on the event handling thread, then yes, your GUI will freeze during that time. A better idea is to use a SwingTimer which will allow you to trigger playing of the second video after a specified delay without calling sleep().

这篇关于有没有更好的或替代的方法来跳过/避免在 Java 中使用 Thread.sleep(1000)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 22:25