Is there any better or alternative way to skip/avo

2019-02-19 19:55发布

问题:

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.

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

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

回答1:

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().



回答2:

as mentioned above, SwingTimer is a good solution

if you want it a little more complicated but self-made start a new Thread to handle the sleeps and new Loads. but I would prefer the SwingTimer too



标签: java swing timer