Page 1 of 4 123 ... LastLast
Results 1 to 20 of 61
Like Tree1Likes

Thread: What is the sense of invokeLater()

  1. #1
    ark
    ark is offline Senior Member
    Join Date
    Apr 2015
    Posts
    288
    Rep Power
    6

    Default What is the sense of invokeLater()

    As well as Invokeand wait.
    I used such code from the net:
    Java Code:
    import java.awt.ComponentOrientation;
    import javax.swing.*;
    
    public class MenuGlueDemo {
    
        public MenuGlueDemo() {
            JMenuBar menuBar = new JMenuBar();
            menuBar.add(createMenu("Menu 1"));
            menuBar.add(createMenu("Menu 2"));
            menuBar.add(createMenu("Menu 3"));
            menuBar.add(new JSeparator());
            menuBar.add(new JButton("   Seach ....  "));
            menuBar.add(new JTextField("   Seach ....  "));
            menuBar.add(new JComboBox(new Object[]{"height", "length", "volume"}));
            menuBar.add(Box.createHorizontalGlue());
            menuBar.add(createMenu("About"));
            JFrame frame = new JFrame("MenuGlueDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(menuBar);
            frame.pack();
            frame.setVisible(true);
        }
    
        public JMenu createMenu(String title) {
            JMenu m = new JMenu(title);
            m.add("Menu item #1 in " + title);
            m.add("Menu item #2 in " + title);
            m.add("Menu item #3 in " + title);
            if (title.equals("About")) {
                m.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
            }
            return m;
        }
    
        public static void main(String[] args) {
         MenuGlueDemo menuGlueDemo = new MenuGlueDemo();
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
    
                @Override
                public void run() {
                    MenuGlueDemo menuGlueDemo = new MenuGlueDemo();
                }
            });
        }
        
    }
    but the result is the same as
    Java Code:
    public static void main(String[] args) {
         MenuGlueDemo menuGlueDemo = new MenuGlueDemo();
        }

  2. #2
    benji2505 is offline Senior Member
    Join Date
    Sep 2014
    Location
    MA, USA
    Posts
    399
    Rep Power
    6

    Default Re: What is the sense of invokeLater()

    the method invoke later() invokes a new thread that is then started by the method run(). Think of threads as processes that run in parallel. The idea behind it is to make things faster, smoother and enable a more intuitive structure.
    Last edited by benji2505; 11-03-2015 at 01:19 AM.

  3. #3
    ark
    ark is offline Senior Member
    Join Date
    Apr 2015
    Posts
    288
    Rep Power
    6

    Default Re: What is the sense of invokeLater()

    Why invoke later - after what? What if I want to use something like join of typical Thread in Swing - If I want to main thread to end the action --for example the appending the text from inputstream to Jtextarea (wholly untill the end) -- and then to be able to do another task??

  4. #4
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,003
    Rep Power
    33

    Default Re: What is the sense of invokeLater()

    Have you read the API doc for the method to see what it does?

    Also look at the tutorial: The Really Big Index
    If you don't understand my response, don't ignore it, ask a question.

  5. #5
    benji2505 is offline Senior Member
    Join Date
    Sep 2014
    Location
    MA, USA
    Posts
    399
    Rep Power
    6

    Default Re: What is the sense of invokeLater()

    Quote Originally Posted by ark View Post
    Why invoke later - after what?
    after you have called the run() method. You don't have to call it right away as in your example.

    You can always end/stop a certain instance of the thread class, but you may want to think about it twice from where and when you stop it.
    With threads you open a can of worms, many results that are difficult to grasp.

  6. #6
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: What is the sense of invokeLater()

    Quote Originally Posted by benji2505 View Post
    The idea behind it is to make things faster, smoother and enable a more intuitive structure.
    Not quite. There is more to it than that. You may want to read this.

    Initial Threads (The Java Tutorials > Creating a GUI With JFC/Swing > Concurrency in Swing)

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  7. #7
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    27

    Default Re: What is the sense of invokeLater()

    Quote Originally Posted by benji2505 View Post
    the method invoke later() invokes a new thread that is then started by the method run().
    As jim says, not quite.
    As the API says, the run() method is executed on the Event Dispatch Thread, which is (essentially) the thread that Swing code executes on.
    Since the construction of the GUI is a Swing thing then all Swing related code should be run on this thread.

    It does not create a new thread.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  8. #8
    ark
    ark is offline Senior Member
    Join Date
    Apr 2015
    Posts
    288
    Rep Power
    6

    Default Re: What is the sense of invokeLater()

    What is the difference between invokeLater() and invokeandWait()? Wait for what?
    So relating question one more - what is the prototype of join() method in Swing, how implement it here, or sleep() method?

  9. #9
    ark
    ark is offline Senior Member
    Join Date
    Apr 2015
    Posts
    288
    Rep Power
    6

    Default Re: What is the sense of invokeLater()

    And in my Task for GUI it was told that the GUI usage should be non-locking so such kind of synchronize keyword in Threads, so how realize it here where just one thread and invokeLater(andWait)?

  10. #10
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: What is the sense of invokeLater()

    Quote Originally Posted by ark View Post
    What is the difference between invokeLater() and invokeandWait()? Wait for what?
    Wait for the invoked process to stop running on the Event Queue. If you invokeLater, the method places the Runnable on the
    event queue and immediately returns. If you do invokeAndWait the method doesn't return until the Runnable has completed.
    Normally I do invokeLater. But if you have other tasks that require immediately using the GUI or whatever target of the invocation, you may want to
    wait until it has fully finished its job, otherwise you may be accessing something before it has finished its initialization.


    So relating question one more - what is the prototype of join() method in Swing, how implement it here, or sleep() method?
    Join just waits for the thread to die. Sleep just sleeps. Here is a small (and very contrived) demo:
    Java Code:
    public class Demo {
       public static void main(String[] args) {
          Thread demoThread = new Thread(new Runnable() {
             public void run() {
                try {
                   Thread.sleep(2000);
                   Thread.currentThread().join(1000); // now wait 1
                                                      // second to
                                                      // die
                }
                catch (InterruptedException ie) {
                   System.out.println("Thread was interrupted");
                }
                finally {
                   System.out.println("Thread is leaving");
                }
             }
          }, "Demo Thread");
          demoThread.start();
          for (int k = 0; k < 20; k++) {
             Thread[] threads = new Thread[10]; // sufficient space
                                                // for threads
             Thread.enumerate(threads);
             System.out.println("----Active Threads-------");
             for (int j = 0; j < Thread.activeCount(); j++) {
                System.out.println(threads[j].getName());
             }
    
             try {
                Thread.sleep(1000); // sleep 1 second
             }
             catch (InterruptedException ie) {
             }
             ;
          }
       }
    }
    Last edited by jim829; 11-05-2015 at 05:43 AM.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  11. #11
    ark
    ark is offline Senior Member
    Join Date
    Apr 2015
    Posts
    288
    Rep Power
    6

    Default Re: What is the sense of invokeLater()

    " -> " -- what this sign means?

  12. #12
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: What is the sense of invokeLater()

    Quote Originally Posted by ark View Post
    " -> " -- what this sign means?
    That is the some of the Java 8 syntax. It represents a lambda expression. Pre-Java 8 you would do it like
    this:

    Java Code:
    Thread demoThread = new Thread(new Runnable() {             
     public void run() {                                      
           try {                                                 
             // do some processing                              
             Thread.currentThread().join(); // now wait to die  
           }                                                     
           catch (InterruptedException ie) {                     
               System.out.println("Thread is kaput!");            
           }                                                     
       }                                                        
    }, "Demo Thread");
    Sorry for the confusion.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  13. #13
    benji2505 is offline Senior Member
    Join Date
    Sep 2014
    Location
    MA, USA
    Posts
    399
    Rep Power
    6

    Default Re: What is the sense of invokeLater()

    The only difference is indicated by their names: invokeLater simply schedules the task and returns; invokeAndWait waits for the task to finish before returning.

    copied from here:
    https://docs.oracle.com/javase/tutor...ncy/index.html

    For the () -> {} expression, check this:

    https://docs.oracle.com/javase/tutor...pressions.html

  14. #14
    ark
    ark is offline Senior Member
    Join Date
    Apr 2015
    Posts
    288
    Rep Power
    6

    Default Re: What is the sense of invokeLater()

    1. I do not understand why arrow brackets (like generics) with 2 integers - SwingWorker<Integer, Integer>.
    What is the sense in SwingWorker in context of commomsense.
    2. The same question on lambda (->) as I have not enough time to be inclusive in it despite at least 2 times noted it in last days (and it were probably first such cases).
    3. invokeLater() - return instantly but continue the task. What return - the content of run()?, but what task is continuing, the same the run() or other task other irrespective to on the run(), but also in EDT – for example in the paint() repaint() method.
    As I understood the realized Thread is some kind of main thread and is pushed by show(), pack() – and its is probably the static (not dynamic) actions.
    f.e.
    Java Code:
    {
    invokeLater(runnableclassobject) {
    textarea.append();
    }
    repaint(); //update() {textarea. setText(""))}; //run () {Jlabel lab=new Jlabel(“new label”);}
    }
    What do return invokeLater () instantly, and which task is continuing in this case?

  15. #15
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    27

    Default Re: What is the sense of invokeLater()

    invokeLater will place the Runnable object onto the EDT queue for it to be executed on the EDT.
    By "return instantly" we mean that the main thread (the one you're in when you start the app, and the one in which invokeLater is called) gets control back and can then do mor stuff.
    Usually it just stops in these sorts of simple apps.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  16. #16
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: What is the sense of invokeLater()

    First, forget about Lambdas. That has nothing to do with invokeLater or invokeAndWait.

    For discussion, assume the following:

    Java Code:
    Runnable task1 = new Runnable() {
        public void run() {
            // do some stuff
        }
    };
    
    try { // this method requires try/catch block
    SwingUtilities.invokeAndWait(task1);
    } catch (InterruptedException ie) {}
    
    // this method does not require try/catch block
    SwingUtilities.invokeLater(task1);
    InvokeAndWait simply means that invokeAndWait will not return until task1 is finished executing.

    InvokeLater means that the invokeLater method will return immediately. Task1 may or may not be finished
    executing when the invokeLater method returns.

    In both cases, task1 is executed on the Event Dispatch Thread.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  17. #17
    ark
    ark is offline Senior Member
    Join Date
    Apr 2015
    Posts
    288
    Rep Power
    6

    Default Re: What is the sense of invokeLater()

    If we for example need to return
    System.out.print(factorial(n)) in run() method - why to return it if have not foundn this factorial of big n.
    Despite I do understand that its about graphics - but why and what return if we have not realized the method(task)?

  18. #18
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: What is the sense of invokeLater()

    Doing that kind of computation is not what the EDT is for. The EDT tasks should be relatively short and not too expensive
    or your GUI will become unresponsive. Use other threads for background tasks which may take a while to complete. Think of a grocery
    store where some check out lines are 10 items or less. That is the EDT. Imagine what happens when someone with two cart loads of groceries
    gets in that line. All other customers in that line (aka tasks in the EDT) are now not being processed in a timely manner because they need to
    wait behind the expensive (and irritating) task.

    Regards,
    Jim
    Last edited by jim829; 11-05-2015 at 05:05 PM.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  19. #19
    ark
    ark is offline Senior Member
    Join Date
    Apr 2015
    Posts
    288
    Rep Power
    6

    Default Re: What is the sense of invokeLater()

    No question is why to return before ending the task -- I think the task is the method- so how to return before the method is done?
    Maybe clear examples.
    For example I had such intention not realized in the spring of this year -- I wanted to draw all lines(roads) by black colours after invocation of one method(with enough computation), then draw just some of these lines in gray colour (also after enough heavy-computation method). So how I should realize this task -- and how invokelater could help here?

  20. #20
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,003
    Rep Power
    33

    Default Re: What is the sense of invokeLater()

    Use invokeLater when you don't want to synchronize the current task with the other task. One use might be when a task is doing a search and wants to show the progress of the search in the GUI. Because changing the GUI needs to be done in the EDT, enqueue the task the do the GUI update with invokeLater and continue the search. Some time later the system will execute the GUI update task on the EDT.
    If you don't understand my response, don't ignore it, ask a question.

Page 1 of 4 123 ... LastLast

Similar Threads

  1. Variation on the Swing invokelater() issue
    By Digital Larry in forum New To Java
    Replies: 3
    Last Post: 05-12-2013, 02:15 AM
  2. SwingUtilities.invokeLater();
    By Lil_Aziz1 in forum New To Java
    Replies: 4
    Last Post: 02-08-2010, 10:11 PM
  3. what is SwingUtilities.invokeLater(new Runnable())
    By sivakumar_sakam in forum AWT / Swing
    Replies: 3
    Last Post: 05-06-2009, 04:47 AM
  4. Use of swingutilities.invokeLater
    By neha_negi in forum AWT / Swing
    Replies: 2
    Last Post: 09-19-2008, 02:48 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •