Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / GUI / February 2004

Tip: Looking for answers? Try searching our database.

swing and threads

Thread view: 
Robert Ludewig - 10 Feb 2004 09:48 GMT
Hello I am trying to undertand the articles abut swing and threads at
java.sun.com. In my following testcode I have one thread that si doing
the work (a simple loop) and another thread that si doing the update
of the dialog to show the progress of the working thread. My fist
questions here are:
Is my code OK? Is it Threadsafe, could there be anything problematic
in this code? Did I work right with my threads and the event
dispatching thread?
The second thing is something rather interesting for me, maybe you can
explain this to me:
As you can see I measured the time the loopthreads runs. And the funny
thing is: When I run it WITH SwingUtilities.invokeAndWait its 30%
faster than without. Why is that so?

import java.awt.*;
import java.awt.event.*;
import java.lang.reflect.*;
import java.util.Calendar;
import javax.swing.*;
public class MyPanel extends JPanel implements ActionListener
{
    JButton button;
    JDialog jd;
    JLabel jlText, jlIcon;
    int i;
    Calendar c;
    int h,m,s,ms,timer2,timer1;
    public MyPanel()
    {
        button = new JButton("show Dialog");
        button.addActionListener(this);
        add(button);
        jd = new JDialog((Frame)SwingUtilities.windowForComponent(this),true);
        jd.getContentPane().setLayout(new FlowLayout());
        jlText = new JLabel("hallo");
        jlIcon = new JLabel (new ImageIcon("progress.gif"));
        jd.getContentPane().add(jlText);
        jd.getContentPane().add(jlIcon);
    }
    public void actionPerformed(ActionEvent e)
    {
        if (e.getSource()==button)
        {
            c = Calendar.getInstance();
            h = c.get(Calendar.HOUR);
            m = c.get(Calendar.MINUTE);
            s = c.get(Calendar.SECOND);
            ms = c.get(Calendar.MILLISECOND);
            timer1 = h*3600000+m*60000+s*1000+ms;
            Runnable r = new Runnable ()
            {
                public void run()
                {
                    for (i =0;i<=99990000;i++)
                    {
                        System.out.print("");
                    }
                    c = Calendar.getInstance();
                    h = c.get(Calendar.HOUR);
                    m = c.get(Calendar.MINUTE);
                    s = c.get(Calendar.SECOND);
                    ms = c.get(Calendar.MILLISECOND);
                    timer2 = h*3600000+m*60000+s*1000+ms;
                    System.out.println(" Time: "+(timer2-timer1));
                }
            };
            Thread t = new Thread (r);
            t.setPriority(Thread.MIN_PRIORITY);
            t.start();
            Thread t2 =new Thread(new Runnable()
                    {
                public void run()
                {
                    while (i<=999900000)
                    {
// uncomment all commented lines to try the faster version                       
//                        try
//                        {
//                            SwingUtilities.invokeAndWait(new Runnable()
//                            {
//                                public void run()
//                                {
                                    jlText.setText(new Integer (i).toString());
//                                }
//                            });
//                        }
//                        catch (InterruptedException e)
//                        {
//                            e.printStackTrace();
//                        }
//                        catch (InvocationTargetException e)
//                        {
//                            e.printStackTrace();
//                        }
//                       
                    }
                }
            });
            t2.setPriority(Thread.MIN_PRIORITY);
            t2.start();
            jd.pack();
            jd.show();
           
        }
    }
}
Xavier Tarrago - 11 Feb 2004 09:09 GMT
1 - You have four threads in your app :
     1 main thread
     2 swing thread
     3 your task thread t1. It increments i
     4 your monitoring thread t2. It changes the text label
When you do NOT use invokeAndWait, you are wrong because you use a swing
object from a thread (t2) that is not the Swing thread.
When you use invokeAndWait, you are right (for the thread aspect) because t2
submit a task (a Runnable) that will be executed by the Swing thread to
update the text field.

2 - there is a side effect. When invoking the text update with
invokeAndWait, your thread t2 is waiting most of the time and your thread t1
runs faster. I would bet that if you set a counter to count the number of
execution of the while loop in t2, you will see much less loops when using
invokeAndWait.

3 - You misuse Calendar. It is an object for formatting date and time. Use
System.currentTimeMillis() instead.

4 - You should initialise i before launching threads because if t2 is
scheduled first, it will use i before it is initialized (by t1)

5 - I am not sure, but accesses to i shoud be synchronized.

> Hello I am trying to undertand the articles abut swing and threads at
> java.sun.com. In my following testcode I have one thread that si doing
[quoted text clipped - 102 lines]
> }
> }


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.