GUI freezes when new Thread object start()ed. Neat, brief code included :)

The title says it all really.. I have the code below in a method startScan() that is called when a button is pressed. The thread executes fine, but the GUI locks up while the thread is executing. I don't really understand why, since a new thread is implicitly separate from the event dispatch thread.
Must I use a SwingWorker to get things working? Would someone be kind enough to explain why, if this is the case?
private void startScan() throws InterruptedException {
          final Runnable breadthFirstComparer = new Runnable() {
               /** Sleep interval used when scan paused */
               private int interval = 1000;
                * Kills the current thread
               public void stop() {
                    scanProgressLabel.setText("Scanning complete");
                    scanComplete = true;
                * Sleeps the currently running thread if user has paused the scan,
                * otherwise initiates comparison of the trees' next depth node sets
               public void run() {
                    while (!scanComplete) {
                         while (scanPaused) {
                              try {
                                   Thread.sleep(interval);
                              } catch (Throwable exc) {
                                   Gecko.logException("Scanner thread could not be paused", exc);
                         compareTrees();
                    // Stop thread execution once scan is complete, and disable
                    // scanner-related buttons
                    toggleScanButton.setEnabled(false);
                    stop();
          scanner = new Thread(breadthFirstComparer)
               public void start() {
                    scanProgressLabel.setText("Scanning in progress...");
                    breadthFirstComparer.run();
          scanButton.setEnabled(false);
          scanner.start();
     }Many thanks.

it's getting really irritating that pretty much every thread out of the last
20 I've made, you've criticised me for not posting an SSCCE. How do you think I feel. I'm donating my time to help you solve a problem, but you are not willing to spend 5-10 minutes to post a SSCCE so that we can fully understand what you have done and what the problem is.
You don't have to post a SSCCE if you don't want to. Thats fine, I just won't answer your questions.
what's the point me spending 30 minutes or more my end creating an
SSCE, and you spending 10 minutes or more compiling, running and analyzing it your end?It should not take 30 minutes. If it does it just goes to prove that you don't really understand what you are attempting to do. And if you don't know what you are doing how do you expect us to guess what you are doing? One of the benefits of a SSCCE it to help you learn to develop problem solving skills by learning to simplfy the problem.
Also, what if we can't figure out the problem based on your verbal description of the problem? If you post code it gives us the option of compiling and testing the code if we so desire. Without the code we give up and move on to the next question.
but since the simple information that you've provided, and the chunk of code that Michal so kindly donated, are likely more than enough of an explanationThis time we were able to guess what the problem was, but that is not true in all cases. You seem to think that we are all miracle workers, that you can place a couple of lines of code in front of us and we can automatically tell whats wrong. Well, thats not true (at least for me). Many times I use my problem solving skills to solve the problem.
I really should learn to scroll down and read all the posting before replying. es5f2000 pretty much said it all for me.
Message was edited by:
camickr

Similar Messages

  • GUI Freezes once socket server is started

    Here's my problem and I am stumped. I have an application which starts a
    socket server and waits for clients to connect. Once connected, the
    server queries XML to the client for display.
    My problem is when I start the server my GUI freezes. I have a simple
    GUI with a start and stop button made in JBuilder. Although the server is running fine and the application works (I can connect and query with my client) the GUI freezes and I have to CTRALTDEL to close the app.
    The method below (see after message) is in the main Application.java class and my GUI is being created in the Frame1.java class. The Frame class has a listener for the button press which calls startServer in
    Application. This was developed in JBuilder Personal edition.
    I keep reading about InvokeLater but not sure if this is what I need. I feel like what is happening is the server starts and the app listens for clients and ignores the GUI.
    Any suggestions would be helpful as madness is setting in.
    Thnaks.
    public static void startServer() {
    try{
    int intPort=9999;
    ServerSocket server = new ServerSocket(intPort);
    System.out.println("Server started...waiting for clients.");
    while(true){
    Socket objSocket = server.accept();
    SocketClient client = new SocketClient(objSocket);
    client.start();
    catch(IOException ioe){
    //dump error
    Here is how the server is being started:
    void button1_actionPerformed(ActionEvent e) {
    try{
    startserver.main(); //make call to start the server
    label2.setText("Running");
    catch (Exception ie) {
    System.err.println("Could not listen on port: 9999.");
    System.exit(-1);
    }

    Swing executes all GUI related code (event handling, painting, etc.) in the so-called event dispatching thread. If you call a blocking method like ServerSocket.accept in this thread, it is blocked and unable to perform further gui tasks.
    public class MyServerThread extends Thread
        private ServerSocket serversocket;
        public void run()
            try
                this.sserversocket = new ServerSocket(9999);
                while(!Thread.interrupted())
                    Socket socket = serversocket.accept();
                    new SocketClient(socket).start();
            catch(IOException ex)
                ex.printStacktract();
        public void shutdown()
            if(this.serversocket != null)
                //closing the socket will cause accept() to throw an exception and therefor quit its loop
                try { this.serversocket.close(); } catch(IOException ignored) {}
                this.interrupt();
                this.serversocket = null;
    //in your GUI class
    private MyServerThread serverthread;
    void startserver()
        serverthread = new MyServerThread();
        serverthread.start();
    void stopserver()
        serverthread.shutdown();
        serverthread = null;
    }

  • Program freezes when a thread is run in another class.

    I have a class that extends Thread, and then I have a GUI that needs this thread.
    The thread class looks like this:
    public class ScoreboardCheck extends Thread
        private int clock;
        private boolean running;
        public ScoreboardCheck(int timeOnClock)
            super();
            this.clock = timeOnClock;
            running = false;
        public int getClock()
            return this.clock;
        public void toggleRunning()
            if (running == false)
                running = true;
            else
                running = false;
        public void run()
            while (Thread.currentThread() == this)
                if (running == true)
                    try
                        Thread.sleep(1000);
                        clock--;
                    catch(InterruptedException ie)
                        ie.printStackTrace();
    }This is suppose to update the clock on the GUI. I instantiate the thread in the GUI class, and call start on it. This works fine, but whenever I call run, it freezes up....Either way it never does anything.
    In the GUI class, how am I suppose to continously update the clock without this thing freezing up? I've tried implementing runnable in the GUI class, but that didn't work.

    Thanks for the replies, guys.
    When I call start it doesn't freeze. That's good. The only other problem I'm faced with, is updating the GUI probably every second. I've tried using a run method in the GUI which runs while true, but that froze things up....This is the point I'm stuck at. For now, I'm going to try what someone suggested: the Timer class. Is there another way of doing this though? Without the timer?

  • IDVD freezes when I try to start a new project.

    I've done everything I can think of but everytime I try to open a new project or open an existing one the application freezes. This is my first time opening iDVD.

    1. Do all the other apps work exactly as expected (except iDvd)?
    2. How much available Hard Drive space do you have on the boot volume?
    3. Is it at least 25GB's?
    4. I need to know if your laptop feels warm to the touch or if the fan has kicked in recently. If so, then you need to allow your laptop to cool for 20-30 minutes. Power it down and let it set for a half hour and try again.
    5. What approaches have you already tried?
    6. Did you try to reinstall iDvd yet?
    7. Have you run apple's software updater?
    8. Do you have any ext. FW or USB devices connected?
    9. Do you have any Non-standard QT plugins on this laptop (yes/no)?
    10. Have you tried switching to a separate user account to see if iDvd will launch on the new account?

  • Indeterminate progressbar freezes when executing thread

    Hi people,
    Here is my problem.
    In my GUI application, at some point the user needs to perform a time consuming application. I want to tell the user that the task is performing as it is supposed to by displaying an undeterminate progressbar. However, when the task is being executed, the progress bar just freezes, until the task is finished. This particular task involves the use of an external process (i.e. .exe file).
    To remedy this, I launch a separate thread to perform my task, using SwingWorker, which, as I understand it, is a class designed for exactly this sort of thing. But it does not work! I spent a lot of time trying to get this problem solve but with no success. I also tried to put the the task in a "conventional" thread, but it always result in the same behavior. Here is some of my code, so someone can maybe see what am I doing wrong. In that code, the progressDialog displays a progressbar set at indeterminate(true);
    Since I successfully used the code below to perform more simple tasks (like reading files and extracting lines from it), I am wondering if the use of an external .exe might be the problem here.
    Cheers,
    progressDialog = new StatusJDialog(new javax.swing.JFrame(), false);
    progressDialog.setVisible(true);
    task = new Task();
    task.execute();
    class Task extends SwingWorker<Void, Void> {
    * Main task. Executed in background thread.
    @Override
    //None GUI stuff goes here.
    public Void doInBackground()  {
           try {
                    Thread.sleep(100);
                    WindowManager.getDefault().invokeWhenUIReady(new Runnable() {
                        public void run() {
                            //Do time consuming task using external .exe here...
                } catch (InterruptedException ignore) {}
                return null;
             * Executed in event dispatch thread
    @Override
    public void done() {
        Toolkit.getDefaultToolkit().beep();
        progressDialog.setVisible(false);
    }

    It looks to me as if you're creating a SwingWorker background thread, but within that background thread, you're placing a long-running task on the EDT with this:
    WindowManager.getDefault().invokeWhenUIReady(new Runnable() {
    }So you're defeating the purpose of the SwingWorker.
    You need to understand that code called in the doInBackground is called off of the EDT. I suggest that you get rid of the code to invoking the WindowManager and simply call your long running task in doInBackground.
    i.e.,
    public Void doInBackground()  {
           try {
                    Thread.sleep(100);
                    //    **** delete block below
                    // WindowManager.getDefault().invokeWhenUIReady(new Runnable() {
                    //     public void run() {
                    //   **** delete block above
                   //  ***  Do time consuming task using external .exe here...  *** 
                } catch (InterruptedException ignore) {}
                return null;
            }For others, a link to the WindowManager API is here: [http://bits.netbeans.org/dev/javadoc/org-openide-windows/org/openide/windows/WindowManager.html#invokeWhenUIReady%28java.lang.Runnable%29]

  • Issue Logic 9 Crashing when new project is started

    i have been having this drama with logic 9 over last few days first it was my mac pro playing up now logic,
    whenever i start up logic everything works fine then when i go to new project, one of my templates or open any project it freezes , what it specifically does is when i got to the finder at top the rainbow pin wheel pops up and it just keeps spinning until i am forced to "force quit"
    included is a log of what happened when it crashed last
    http://www.speedyshare.com/files/23872264/logiceffor_report_19082010.rtf
    PS i am using a OSX 10.5.8 / Macpro Intel Xeon 2.66 Quadcore late 08 model
    any help would be appreciated

    yes i am using latest version of logic with Project mix i/o and novation remote keyboard (something in my head was telling me that auto map might of done this but after i uninstalled still had dramas)
    every this looks ok until i got the finder then the rainbow pin wheel of death pops up and will not go away until i force quit , even bloody cubase seems to be working right

  • VMware Fusion Freezes when i try to start it.

    Hey guys, i have encountered a problem with Vmware fusion today. When i tried to turn it on it froze on me so i restarted my computer, after doing that I tried to run it again and as soon as it got up to the Windows XP screen it just freezes, i cant even move my mouse. Another restart after that gets me to the screen where i can choose Safe mode or normal mode, and when i choose safe mode it runs some commands and freezes again.
    Also prior to the problem i used to just Suspend the VM all the time and exit out of the program instead of shutting it down. I am not sure if that caused it but that is just some extra info. I also tried updating it to the newest version but that did not help either.
    So i am wondering is there anyway to save what i have on that VM? Or do i have to just uninstall, reinstall and make a whole new VM.
    Thanks for the help.

    Fusion is a third-party product. Perhaps you should visit their forum to see if someone there can help you.

  • Router freezes when New iPad connects

    Trying to download a newspaper paid by subscriptions.  Loads about 9% and then freezes.Don't know if this is a fault with the iPad or whether I should get a new router.  Nothing else causes the router to freeze.

    Router problem. How old is the router and when was the last time you checked the manufacturer's website for a firmware update?

  • Windows Freezes When New Ipod 60gb plugged in

    When I plug in my video ipod, my windows xp will slow down. I can click things in the desktop and nothing will happen. Sometimes I cant click the start menu. It shows that the "new hardware" is plugged in. If I unplug it, all the things i clicked on open and windows runs fine. If I leave the ipod plugged in for a few minutes, like 2-5, it will eventually open up itunes and connect to the ipod but I dont like how slow it takes to connect. Does anyone know why this would be happening?

    Same Problem with a Dimension 4500 with USB 2.0 so I am not sure that's the problem. It appears to be all about being patient for the PC to recognize the IPOD and get Itunes up and running. The things get better.
    When updating the IPOD I get a message after 50 or so MB are transferred that the update has stopped because the disk is not accessible.
    My guess on all this is that there is a incompatibility with the USB drivers

  • How do I stop all tab group windows cascade open when new page is started

    Upgrade to latest Firefox version two days ago, and now whenever I start a NEW PAGE, all tabbed pages cascade onscreen, ie "open link in new window" brings up all tab groups on toolbar.
    This has never been a problem - I "save" windows in Tab Groups on my toolbar, and bring up a Group for reference during the day.
    Something in the new download has altered my settings, and I cannot find how to keep the tabbed window groups from cascading onscreen, and having to constantly minimise them.

    Start Firefox in <u>[[Safe Mode]]</u> to check if one of the extensions is causing the problem (switch to the DEFAULT theme: Firefox (Tools) > Add-ons > Appearance/Themes).
    * Don't make any changes on the Safe mode start window.
    * https://support.mozilla.com/kb/Safe+Mode
    * https://support.mozilla.com/kb/Troubleshooting+extensions+and+themes

  • Macbook Air Freezes when Time Machine backup starts

    My Macbook Air (OS 10.5.5) has started freezing up whenever a Time Machine backup begins. I get the dark shade screen telling me that it has crashed and to hard power off. Everything was working well before, including the Time Machine backups, and the only changes I have made are the Apple updates. At first I thought it was random crashes, but I soon discovered that turning off Time Machine stops the problem (though obviously does not fix it). I've tried restarting and turning Time Machine back on, but it still makes the computer crash within a minute of the start of the backup process. The backup goes to a Time Capsule. I have not seen this problem on any of my other macs on the same network including a Macbook Pro that backs up to the same Time Capsule. Does anyone have any idea what the problem could be and how to fix it?

    To be honest,no I don't know why you are having this problem.
    It looks like a specific problem with your MBA which could be a hardware problem (RAM most likely here) or a bad sector problem on the hard disk. If you own a copy of TechTool or something similar, run a full hardware systems check. If you don't own TechTool, run the Apple Hardware check from the MBA System install disk.
    And, it could be a software problem. I don't know if this sequence will help, but do it anyway because it seems to solve problems on other Leopard systems.
    1.) Disable Time Machine back ups
    2.) Open Disk Utility and Run Repair Permissions
    3.) Run Verify Disk. If it passes go to step 4.
    4.) Download the 10.5.5. Combo Updater from http://support.apple.com/downloads/MacOS_X_10_5_5_ComboUpdate
    5.) Run the Combo Updater and restart
    6.) Run Disk Utility Repair Permissions again
    Then enable Time Machine and keep your fingers crossed.
    Let me know if any of that helps.

  • My mac book pro freezes when I try to start it

    All I get is a white/grey screen with the apple logo and the progress wheel. Is it dead?

    Problems such as yours are sometimes caused by files that should belong to you but are locked or have wrong permissions. This procedure will check for such files. It makes no changes and therefore will not, in itself, solve your problem.
    First, empty the Trash.
    Triple-click the line below on this page to select it, then copy the selected text to the Clipboard (command-C):
    find ~ $TMPDIR.. \( -flags +sappnd,schg,uappnd,uchg -o ! -user $UID -o ! -perm -600 -o -acl \) 2> /dev/null | wc -l
    Launch the Terminal application in any of the following ways:
    ☞ Enter the first few letters of its name into a Spotlight search. Select it in the results (it should be at the top.)
    ☞ In the Finder, select Go ▹ Utilities from the menu bar, or press the key combination shift-command-U. The application is in the folder that opens.
    ☞ Open LaunchPad. Click Utilities, then Terminal in the icon grid.
    Paste into the Terminal window (command-V). The command may take a noticeable amount of time to run. Wait for a new line ending in a dollar sign (“$”) to appear.
    The output of this command, on a line directly below what you entered, will be a number such as "41." Please post it in a reply.

  • Thread Objects?

    Hi, I need help on making thread objects. I have some code similar to this. It runs as an applet.
    //ThreadTest
    import java.awt.*;
    import java.applet.Applet;
    public class ThreadTest extends Applet {
         public void init() {
              new ThreadObject().start();
    public void paint(Graphics g) {
    g.drawstring(""+i,50,50)
    //this is a new file
    //ThreadObject
    public class ThreadObject extends Thread {
         public ThreadObject() {
              for (int i=0;i>9;i++) {
                   System.out.println(i);
    Im trying to make this thread just dispay the numbers 1-9 (I understand that it should only print 9 because it prints i to the coordinates 50,50, so the numbers will overlap)
    but the screen just stays grey. Ive tried changeing the programs tons of times, but I cant get it to work. Please help!

    Ok, first of all, when you extend Thread the code that will be run should be put in the run() method, second, the variable i is only relevent within the for loop, and has nothing to do with the applet, so your line g.drawString(""+i, 50, 50) will not draw i onto the applet, third, there is no code to repaint the applet when you make changes. Take a look at this... I haven't tested it, but it should be about right: //ThreadTest
    import java.awt.*;
    import java.applet.Applet;
    public class ThreadTest extends Applet {
    int var = 0; //This varable holds the number to display
      public void init() {
        new ThreadObject(this).start(); /* I'm having this object send a refference
                                        // to itself so the thread has a way to
                                        // call the repaint method */
      public void update(int i) {
        var = i;
        repaint();
      public void paint(Graphics g) {
        g.drawstring("" + var,50,50)
    public class ThreadObject extends Thread {
    Applet parent;
      public ThreadObject(Applet p) {
        parent = p;
      public void run() {
        for (int i=0;i>9;i++) {
          parent.update(i);
          try {
            Thread.currentThread().sleep(500);/*I'm having the Thread sleep
                                              //for 1/2 second between numbers
                                              */so you can see the numbers change
          } catch(Exception e){System.out.println("Exception: " + e);}
    }Like I said, I haven't tested this, so there may be some little problem, but I think that should be about it.
    Hope it helps
    webaf409java

  • Throwing Exceptions from a new Thread

    Please help if you can.........
    I have a very simple RMI server, that is used to run processes in seperate threads on a server machine, that are kicked off by a client GUI.
    All works fine, except if the process can not be found, then the server generates an IOException. How can I get the thread to throw the exception back to the RMI Server, and then back to the GUI.
    I have tried to throw Runtime Exceptions but that did not work, and I can not declare the run method of the thread to throw a remote exception......
    Any help would be most appriciated...
    G

    /* the listener interface */
    public interface ExceptionListener {
      void exceptionOccured(Throwable t);
    /* the runnable object */
    public class WorkerThread implements Runnable {
      List exceptionListenerList;
      public void addExceptionListener(ExceptionListener l) {
        exceptionListenerList(l);
      public void run() {
        try {
        // do the work, e.g some JDBC stuff
        } catch(Throwable t) {
          // error occured, first do some logging, then notify all listeners
          t.printStackTrace();
          for(i=0; i<exceptionListenerList; i++) {
            (ExceptionListener)exceptionListenerList.get(i).exceptionOccured(t);
    /* this clas creates and & runs the thread; before doing this it
    registers itself as an ExceptionListener to the runnable object */
    public class ThreadStarter implements ExceptionListener {
      public final void exceptionOccured(Throwable t) {
        // do whatever you want to do with the exception
      public final void startThread() {
        WorkerThread wt = WorkerThread();
        wt.addExceptionListener(this);
        new Thread(wt).start();
    }By the way: I "borrowed" the ExceptionListener / ExceptionCallback idea from the book "java thread programming - the authorative solution" by paul hyde.

  • Which thread will start first?

    Hi,
    I have a very basic question for you folks, considering the following example code,
    new thread(new Runnable(){
    public void run(){
    TestThread t1 = new Thread();
    t1.start();
    }).start();
    Now the question is which thread will start first. The outer one or t1?
    Any explanation would be greatly appreciated.
    /khurram

    Sorry - I should have been more clear
    Runnable r = new Runnable() {
      public void run() {
    }; //the run() method has not been called yet!
    r.run(); //now it has!is defining a class which is to be instantiated. By "defining" a class, I mean providing an implementation of one of the class's methods. This method will not be invoked until explicitly called on the Object "r". The is exactly what is done when the start() is called on the outer thread. Is this a bit clearer?

Maybe you are looking for