Problem with threads and graphics

I have a thread that chooses paths for a Travelling salesman problem, it then calls a TSPdraw class and passes it the path, which the class then draws. the problem is when i have two threads it creates two windows but only draws a path in one of them. any ideas where i`m going wrong

Are you using swing components? Swing isn't threadsafe. If you have multiple threads that want to update your UI you need to use the SwingUtilities.invokeLater(...)or invokeAndWait(...). There is a page in the swing tutorial about this at: http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html

Similar Messages

  • Problem with Thread and InputStream

    Hi,
    I am having a problem with threads and InputStreams. I have a class which
    extends Thread. I have created and started four instances of this class. But
    only one instance finishes its' work. When I check the state of other three
    threads their state remains Runnable.
    What I want to do is to open four InputStreams which are running in four
    threads, which reads from the same url.
    This is what I have written in my thread class's run method,
    public void run()
         URL url = new URL("http://localhost/test/myFile.exe");
    URLConnection conn = url.openConnection();
    InputStream istream = conn.getInputStream();
    System.out.println("input stream taken");
    If I close the input stream at the end of the run method, then other threads
    also works fine. But I do not want to close it becuase I have to read data
    from it later.
    The file(myFile.exe) I am trying to read is about 35 MB in size.
    When I try to read a file which is about 10 KB all the threads work well.
    Plz teach me how to solve this problem.
    I am using JDK 1.5 and Win XP home edition.
    Thanks in advance,
    Chamal.

    I dunno if we should be doing such things as this code does, but it works fine for me. All threads get completed.
    public class ThreadURL implements Runnable
        /* (non-Javadoc)
         * @see java.lang.Runnable#run()
        public void run()
            try
                URL url = new URL("http://localhost:7777/java/install/");
                URLConnection conn = url.openConnection();
                InputStream istream = conn.getInputStream();
                System.out.println("input stream taken by "+Thread.currentThread().getName());
                istream.close();
                System.out.println("input stream closed by "+Thread.currentThread().getName());
            catch (MalformedURLException e)
                System.out.println(e);
                //TODO Handle exception.
            catch (IOException e)
                System.out.println(e);
                //TODO Handle exception.
        public static void main(String[] args)
            ThreadURL u = new ThreadURL();
            Thread t = new Thread(u,"1");
            Thread t1 = new Thread(u,"2");
            Thread t2 = new Thread(u,"3");
            Thread t3 = new Thread(u,"4");
            t.start();
            t1.start();
            t2.start();
            t3.start();
    }And this is the o/p i got
    input stream taken by 2
    input stream closed by 2
    input stream taken by 4
    input stream closed by 4
    input stream taken by 3
    input stream closed by 3
    input stream taken by 1
    input stream closed by 1
    can u paste your whole code ?
    ram.

  • A problem with Threads and MMapi

    I am tring to execute a class based on Game canvas.
    The problem begin when I try to Play both a MIDI tone and to run an infinit Thread loop.
    The MIDI tone "Stammers".
    How to over come the problem?
    Thanks in advance
    Kobi
    See Code example below:
    import java.io.IOException;
    import java.io.InputStream;
    import javax.microedition.lcdui.Graphics;
    import javax.microedition.lcdui.Image;
    import javax.microedition.lcdui.game.GameCanvas;
    import javax.microedition.media.Manager;
    import javax.microedition.media.MediaException;
    import javax.microedition.media.Player;
    public class MainScreenCanvas extends GameCanvas implements Runnable {
         private MainMIDlet parent;
         private boolean mTrucking = false;
         Image imgBackgound = null;
         int imgBackgoundX = 0, imgBackgoundY = 0;
         Player player;
         public MainScreenCanvas(MainMIDlet parent)
              super(true);
              this.parent = parent;
              try
                   imgBackgound = Image.createImage("/images/area03_bkg0.png");
                   imgBackgoundX = this.getWidth() - imgBackgound.getWidth();
                   imgBackgoundY = this.getHeight() - imgBackgound.getHeight();
              catch(Exception e)
                   System.out.println(e.getMessage());
          * starts thread
         public void start()
              mTrucking = true;
              Thread t = new Thread(this);
              t.start();
          * stops thread
         public void stop()
              mTrucking = false;
         public void play()
              try
                   InputStream is = getClass().getResourceAsStream("/sounds/scale.mid");
                   player = Manager.createPlayer(is, "audio/midi");
                   player.setLoopCount(-1);
                   player.prefetch();
                   player.start();
              catch(Exception e)
                   System.out.println(e.getMessage());
         public void run()
              Graphics g = getGraphics();
              play();
              while (true)
                   tick();
                   input();
                   render(g);
          * responsible for object movements
         private void tick()
          * response to key input
         private void input()
              int keyStates = getKeyStates();
              if ((keyStates & LEFT_PRESSED) != 0)
                   imgBackgoundX++;
                   if (imgBackgoundX > 0)
                        imgBackgoundX = 0;
              if ((keyStates & RIGHT_PRESSED) != 0)
                   imgBackgoundX--;
                   if (imgBackgoundX < this.getWidth() - imgBackgound.getWidth())
                        imgBackgoundX = this.getWidth() - imgBackgound.getWidth();
          * Responsible for the drawing
          * @param g
         private void render(Graphics g)
              g.drawImage(imgBackgound, imgBackgoundX, imgBackgoundY, Graphics.TOP | Graphics.LEFT);
              this.flushGraphics();
    }

    You can also try to provide a greater Priority to your player thread so that it gains the CPU time when ever it needs it and don't harm the playback.
    However a loop in a Thread and that to an infinite loop is one kind of very bad programming, 'cuz the loop eats up most of your CPU time which in turn adds up more delays of the execution of other tasks (just as in your case it is the playback). By witting codes bit efficiently and planning out the architectural execution flow of the app before start writing the code helps solve these kind of issues.
    You can go through [this simple tutorial|http://oreilly.com/catalog/expjava/excerpt/index.html] about Basics of Java and Threads to know more about threads.
    Regds,
    SD
    N.B. And yes there are more articles and tutorials available but much of them targets the Java SE / EE, but if you want to read them here is [another great one straight from SUN|http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html] .
    Edited by: find_suvro@SDN on 7 Nov, 2008 12:00 PM

  • Problem with Threads and a static variable

    I have a problem with the code below. I am yet to make sure that I understand the problem. Correct me if I am wrong please.
    Code functionality:
    A timer calls SetState every second. It sets the state and sets boolean variable "changed" to true. Then notifies a main process thread to check if the state changed to send a message.
    The problem as far I understand is:
    Assume the timer Thread calls SetState twice before the main process Thread runs. As a result, "changed" is set to true twice. However, since the main process is blocked twice during the two calls to SetState, when it runs it would have the two SetState timer threads blocked on its synchronized body. It will pass the first one, send the message and set "changed" to false since it was true. Now, it will pass the second thread, but here is the problem, "changed" is already set to false. As a result, it won't send the message even though it is supposed to.
    Would you please let me know if my understanding is correct? If so, what would you propose to resolve the problem? Should I call wait some other or should I notify in a different way?
    Thanks,
    B.D.
    Code:
    private static volatile boolean bChanged = false;
    private static Thread objMainProcess;
       protected static void Init(){
            objMainProcess = new Thread() {
                public void run() {
                    while( objMainProcess == Thread.currentThread() ) {
                       GetState();
            objMainProcess.setDaemon( true );
            objMainProcess.start();
        public static void initStatusTimer(){
            if(objTimer == null)
                 objTimer = new javax.swing.Timer( 1000, new java.awt.event.ActionListener(){
                    public void actionPerformed( java.awt.event.ActionEvent evt){
                              SetState();
        private static void SetState(){
            if( objMainProcess == null ) return;
            synchronized( objMainProcess ) {
                bChanged = true;
                try{
                    objMainProcess.notify();
                }catch( IllegalMonitorStateException e ) {}
        private static boolean GetState() {
            if( objMainProcess == null ) return false;
            synchronized( objMainProcess ) {
                if( bChanged) {
                    SendMessage();
                    bChanged = false;
                    return true;
                try {
                    objMainProcess.wait();
                }catch( InterruptedException e ) {}
                return false;
        }

    Thanks DrClap for your reply. Everything you said is right. It is not easy to make them alternate since SetState() could be called from different places where the state could be anything else but a status message. Like a GREETING message for example. It is a handshaking message but not a status message.
    Again as you said, There is a reason I can't call sendMessage() inside setState().
    The only way I was able to do it is by having a counter of the number of notifies that have been called. Every time notify() is called a counter is incremented. Now instead of just checking if "changed" flag is true, I also check if notify counter is greater than zero. If both true, I send the message. If "changed" flag is false, I check again if the notify counter is greater than zero, I send the message. This way it works, but it is kind of a patch than a good design fix. I am yet to find a good solution.
    Thanks,
    B.D.

  • Problem with threads and ProgressMonitor

    Dear Friends:
    I have a little problem with a thread and a ProgressMonitor. I have a long time process that runs in a thread (the thread is in an separate class). The thread has a ProgressMonitor that works fine and shows the tasks progress.
    But I need deactivate the main class(the main class is the user interface) until the thread ends.
    I use something like this:
    LongTask myTask=new LongTask();
    myTask.start();
    myTask.join();
    Now, the main class waits for the task to end, but the progress monitor don`t works fine: it shows only the dialog but not the progress bar.
    What's wrong?

    Is the dialog a modal dialog? This can block other UI updates.
    In general, you should make sure that it isn't modal, and that your workThread has a fairly low priority so that the UI can do its updating

  • Problem with threads and/or memory

    I'm developing an application where there are 3 threads. One of them sends a request to the other, and if the 2nd can't answer it, it sends it to the 3rd (similar to CPU -> CACHE -> MEMORY). When i run the program with 1000-10.000 requests, no problem occurs. When i run it with 300.000-1.000.000 requests, it sometimes hangs. Is this a problem with the garbage collector, or should it be related to the threads mecanism.
    (note: eache thread is in execution using a finite state machine)

    i had been running the program inside Netbeans.
    Running the jar using the command line outside
    Netbeans i have no more problems... Does Netbeans use
    it's own JVM?Depends how you set it up, but look under the options. There are settings for the compiler and jvm that it uses.

  • Problem with threads and camera.

    Hi everybody!
    I've a problem with taking snapshot.
    I would like to display a loading screen after it take snapshot ( sometimes i
    have to wait few seconds after i took snapshot. Propably photo is being taken in time where i have to wait).
    I was trying to use threads but i didn't succeed.
    I made this code:
    display.setCurrent(perform);               
            new Thread(new Runnable(){
                public void run() {               
                    while((!performing.isShown()) && (backgroundCamera.isShown())){
                        Thread.yield();
                    notifyAll();
            }).start();
            new Thread(new Runnable(){
                public void run() {
                    try {
                        this.wait();                   
                    } catch(Exception e) {
                        exceptionHandler(e);
                    photo = camera.snapshot();                               
                    display.setCurrent(displayPhoto);
            }).start();This code is sometimes showing performing screen but sometimes no.
    I don't know why. In my opinion performing.isShown() method isn't working correctly.
    Does anyone have some idea how to use threads here?

    Hi,
    I've finally managed to work this fine.
    The code:
           Object o = new Object();
           display.setCurrent(perform);               
            new Thread(new Runnable(){
                public void run() {               
                    while(!performing.isShown()){
                        Thread.yield();
                   synchronized(o) {
                      o.notify();
            }).start();
            new Thread(new Runnable(){
                public void run() {
                    try {
                        synchronized(o) {
                           o.wait(1);
                    } catch(Exception e) {
                        exceptionHandler(e);
                    photo = camera.snapshot();                               
                    display.setCurrent(displayPhoto);
            }).start();

  • Having a problem with threads and using locks

    I was hoping someone could give me some hits on getting my code to run properly. The problem I am having is I think my locks and unlocks are not working properly. Plus, for some reason I always get the same output, which is:
    Withdrawal Threads         Deposit Threads            Balance
    Thread 2 attempts $29 Withdrawal - Blocked - Insufficient Funds
    Thread 4 attempts $45 Withdrawal - Blocked - Insufficient Funds
    Thread 6 attempts $34 Withdrawal - Blocked - Insufficient Funds
    Thread 7 attempts $40 Withdrawal - Blocked - Insufficient Funds
                                    Thread 1 deposits $187          $187
                                    Thread 3 deposits $169          $356
                                    Thread 5 deposits $61           $417
    Press any key to continue...If someone can see the error I made and doesn't mind explaining it to me, so I can learn from it, I would appreciate that very much.
    /************Assign2_Main.java************/
    import java.util.concurrent.*;
    public class Assign2_Main
    {//start Assign2_Main
        public static void main(String[] args)
        {//start main
               // create ExecutorService to manage threads
               ExecutorService threadExecutor = Executors.newCachedThreadPool();
            Account account = new SynchronizedThreads();
            Deposit deposit1 = new Deposit(account, "Thread 1");
            Deposit deposit2 = new Deposit(account, "Thread 3");
            Deposit deposit3 = new Deposit(account, "Thread 5");
            Withdrawal withdrawal1 = new Withdrawal(account, "Thread 2");
            Withdrawal withdrawal2 = new Withdrawal(account, "Thread 4");
            Withdrawal withdrawal3 = new Withdrawal(account, "Thread 6");
            Withdrawal withdrawal4 = new Withdrawal(account, "Thread 7");
            System.out.println("Withdrawal Threads\t\tDeposit Threads\t\t\tBalance");
            System.out.println("------------------\t\t---------------\t\t\t-------\n");
            try
                threadExecutor.execute(withdrawal1);       
                threadExecutor.execute(deposit1);     
                threadExecutor.execute(withdrawal2);  
                threadExecutor.execute(deposit2);    
                threadExecutor.execute(withdrawal3);
                threadExecutor.execute(deposit3);       
                threadExecutor.execute(withdrawal4);
            catch ( Exception e )
                 e.printStackTrace();
                //shutdown worker threads
               threadExecutor.shutdown();
        }//end main
    }//end Assign2_Main/******************Withdrawal.java****************************/
    public class Withdrawal implements Runnable
    {//start  class Withdrawal
          *constructor
        public Withdrawal(Account money, String n)
             account = money;
             name = n;
        public void run()
        {//start ruin
             int newNum = 0;
                newNum = account.getBalance(name); 
               Thread.yield();
        }//end run
        private Account account;
        private String name;
    }//end  class Withdrawal/*******************Deposit.java***************/
    import java.util.Random;
    public class Deposit implements Runnable
    {//start class Deposit
          *constructor
        public Deposit(Account money, String n)
             account = money;
             name = n;
        public void run()
        {//start run
                try
                     Thread.sleep(100);
                   account.setBalance(random.nextInt(200), name);
                }// end try
                catch (InterruptedException e)
                  e.printStackTrace();
       }//end run
       private Account account;
       private Random random = new Random();
       private String name;
    }//end class Deposit/********************Account.java*****************/
    *Account interface specifies methods called by Producer and Consumer.
    public interface Account
         //place sum into Account
         public void setBalance(int sum, String name);
         //return  value of Account
            public int getBalance(String name);         
    } /**************SynchronizedThreads.java****************/
    import java.util.concurrent.locks.*;
    import java.util.Random;
    public class SynchronizedThreads implements Account
    {//start SynchronizedThreads
          *place money into buffer
        public void setBalance(int amount, String name)
        {//start setBalance
             // lock object
             myLock.lock();           
            sum += amount;
            System.out.println("\t\t\t\t" + name + " deposits $" + amount +"\t\t$"+ sum+"\n");       
               //threads are singnaled to wakeup
            MakeWD.signalAll();
              // unlock object                                                
            myLock.unlock();
           }//end setBalance
            *gets the balance from buffer
           public int getBalance(String name)
        {//start getBalance
             int NewSum = random.nextInt(50);
             //lock object
            myLock.lock();
            try
                 if(sum > NewSum)
                     //takes NewSum away from the account
                     sum -= NewSum;
                        System.out.println(name + " withdraws $" + NewSum +"\t\t\t\t\t\t$"+ sum+"\n");
                else
                     System.out.println(name +  " attempts $" + NewSum + " Withdrawal - Blocked - Insufficient Funds\n");                 
                     //not enough funds so thread waits
                        MakeWD.await();         
                //threads are singnaled to wakeup
                MakeD.signalAll();     
                }//end try
            catch (InterruptedException e)
                   e.printStackTrace();
            finally
                 //unlock object
                 myLock.unlock();
            return NewSum;     
         }//end getBalance
         private Random random = new Random();  
         private Lock myLock = new ReentrantLock();
         private Condition MakeD = myLock.newCondition();
         private Condition MakeWD = myLock.newCondition();
         private int sum = 0;
    }//end SynchronizedThreads

    You can also try to provide a greater Priority to your player thread so that it gains the CPU time when ever it needs it and don't harm the playback.
    However a loop in a Thread and that to an infinite loop is one kind of very bad programming, 'cuz the loop eats up most of your CPU time which in turn adds up more delays of the execution of other tasks (just as in your case it is the playback). By witting codes bit efficiently and planning out the architectural execution flow of the app before start writing the code helps solve these kind of issues.
    You can go through [this simple tutorial|http://oreilly.com/catalog/expjava/excerpt/index.html] about Basics of Java and Threads to know more about threads.
    Regds,
    SD
    N.B. And yes there are more articles and tutorials available but much of them targets the Java SE / EE, but if you want to read them here is [another great one straight from SUN|http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html] .
    Edited by: find_suvro@SDN on 7 Nov, 2008 12:00 PM

  • Problem with Threads and "plase wait..."-Window

    Hi everyone,
    I have a problem that I'm not able to solve in any way... I have a time-consuming task (a file decryption) which I execute in a separate thread; I've used the SwingWorker class, like suggested by sun-tutorial, and it works right. The problem is that I have to wait that the decryption have finished before continuing with program-execution. Therefore I would like to display a "please wait"-window while the task runs. I've tryed all the possible ways I know but the problem is always the same: the waitWindow is displayed empty, the bounds are painted but the contents no; it's only painted when the decrypt-task has finished. Please help me, I have no more resources....
    decrypt-file code:
    public class DecryptFile {
      private String cryptedFileNameAndPath;
      private ByteArrayInputStream resultStream = null;
      // need for progress
      private int lengthOfTask;
      private int current = -1;
      private String statMessage;
      public DecryptFile(String encZipFileNameAndPath) {
        cryptedFileNameAndPath = encZipFileNameAndPath;
        //Compute length of task...
        // 0 for indeterminate
        lengthOfTask = 0;
      public ByteArrayInputStream getDecryptedInputStream() {
        return this.resultStream;
       * Called from ProgressBarDemo to start the task.
      public void go() {
        current = -1;
        final SwingWorker worker = new SwingWorker() {
          public Object construct() {
            return new ActualTask();
        worker.start();
       * Called from ProgressBarDemo to find out how much work needs
       * to be done.
      public int getLengthOfTask() {
        return lengthOfTask;
       * Called from ProgressBarDemo to find out how much has been done.
      public int getCurrent() {
        return current;
      public void stop() {
        current = lengthOfTask;
       * Called from ProgressBarDemo to find out if the task has completed.
      public boolean done() {
        if (current >= lengthOfTask)
          return true;
        else
          return false;
      public String getMessage() {
        return statMessage;
       * The actual long running task.  This runs in a SwingWorker thread.
      class ActualTask {
        ActualTask () {
          current = -1;
          statMessage = "";
          resultStream = AIUtil.getInputStreamFromEncZip(cryptedFileNameAndPath); //here the decryption happens
          current = 0;
          statMessage = "";
      }The code that calls decryption and displays waitWindow
          final WaitSplash wS = new WaitSplash("Please wait...");
          final DecryptFile cryptedTemplate = new DecryptFile (this.templateFile);
          cryptedTemplate.go();
          while (! cryptedTemplate.done()) {
            try {
              wait();
            } catch (Exception e) { }
          this.templateInputStream = cryptedTemplate.getDecryptedInputStream();
          wS.close();Thanks, thanks, thanks in advance!
    Edoardo

    Maybe you can try setting the priority of the long-running thread to be lower? so that the UI will be more responsive...

  • Problems with Facebook and graphics?

    About a week ago i notice the lag time in typing is terrible and i must wait for the keyboard to catch up with me.  Now, the pictures and other graphics interfaces on Facebook are all screwed up.  I click on a picture in someone's timeline and the photo just starts to blink.  Sometime a cover photo on a friends page just does wierd things and blinks or even moves into strange positons.  I do not know when the last update to the graphic chip was, but is anyone else having this problem?  Sometimes it happens on twitter, but i think that is about all.  I really dont see it on web sites.
    i have a 15 inch macbook pro, retina, 16 MB of ram, SSD bought last july.

    Contact Facebook & Twitter customer support to determine if the issue is on their end. 
    How large is your hard drive and how much hard drive space do you have left? If you have Apple Care or are still under your 90 days of free phone tech support, call them. 

  • Problem with threads and simulation: please help

    please help me figure this out..
    i have something like this:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class DrawShapes extends JApplet{
         private JButton choices[];
         private String names[]={"line", "square", "oval"};
         private JPanel buttonPanel;
         private DrawPanel drawingArea;
         private int width=300, height=200;
         public void init(){
              drawingArea=new DrawPanel(width, height);
              choices=new JButton[names.length];
              buttonPanel=new JPanel();
              buttonPanel.setLayout(new GridLayout(1, choices.length));
              ButtonHandler handler=new ButtonHandler();
              for(int i=0; i<choices.length; i++){
                   choices=new JButton(names[i]);
                   buttonPanel.add(choices[i]);
                   choices[i].addActionListener(handler);
              Container c=getContentPane();
              c.add(buttonPanel, BorderLayout.NORTH);
              c.add(drawingArea, BorderLayout.CENTER);
         }//end init
         public void setWidth(int w){
              width=(w>=0 ? w : 300);
         public void setHeight(int h){
              height=(h>=0 ? h : 200);
         /*public static void main(String args[]){
              int width, height;
              if(args.length!=2){
                   height=200; width=300;
              else{
                        width=Integer.parseInt(args[0]);
                        height=Integer.parseInt(args[1]);
              JFrame appWindow=new JFrame("An applet running as an application");
              appWindow.addWindowListener(
                   new WindowAdapter(){
                        public void windowClosing(WindowEvent e){
                             System.exit(0);
              DrawShapes appObj=new DrawShapes();
              appObj.setWidth(width);
              appObj.setHeight(height);
              appObj.init();          
              appObj.start();
              appWindow.getContentPane().add(appObj);
              appWindow.setSize(width, height);
              appWindow.show();
         }//end main*/
         private class ButtonHandler implements ActionListener{
              public void actionPerformed(ActionEvent e){
                   for(int i=0; i<choices.length; i++){
                        if(e.getSource()==choices[i]){
                             drawingArea.setCurrentChoice(i);
                             break;
    }//end class DrawShapes
    class DrawPanel extends JPanel{
         private int currentChoice=-1;
         private int width=100, height=100;
         public DrawPanel(int w, int h){
              width=(w>=0 ? w : 100);
              height=(h>=0 ? h : 100);
         public void paintComponent(Graphics g){
              super.paintComponent(g);
              switch(currentChoice){
                   case 0:     g.drawLine(randomX(), randomY(), randomX(), randomY());
                             break;
                   case 1: g.drawRect(randomX(), randomY(), randomX(), randomY());
                             break;
                   case 2: g.drawOval(randomX(), randomY(), randomX(), randomY());
                             break;
         public void setCurrentChoice(int c){
              currentChoice=c;
              repaint();          
         private int randomX(){
              return (int) (Math.random()*width);
         private int randomY(){
              return (int) (Math.random()*height);
    }//end class drawPanel
    That one's from a book. I used that code to start with my applet. Mine calls different merthod from the switch cases. Say I have:
    case 0: drawStart(g); break;
    public void drawStart(Graphics g){
      /* something here */
    drawMain(g);
    public void drawMain(graphics g){
    g.drawString("test", x, y);
    //here's where i'm trying to pause
    //i've tried placing Thread.sleep between these lines
    g.drawLine(x, y, a, b);
    //Thread.sleep here
    g.drawRect(x, y, 50, 70);
    }I also need to put delays between method calls but I need to synchronize them. Am I doing it all wrong? The application pauses or sleeps but afterwards, it still drew everything all at once. Thanks a lot!

    It is. Sorry about that. Just answer any if you want to. I'd appreciate your help. Sorry again if it caused you anything or whatever. .n_n.

  • A problem with Threads and loops.

    Hi, I have some code that needs to be constantly running, like while(true)
          //code here
    }However, the code just checks to see if the user has input anything (and then if the user has, it goes to do some other stuff) so I don't need it constantly running and hogging up 98% of the CPU. So I made my class (which has the method that needs to be looped, call it ClassA) implement Runnable. Then I just added the method which needed to be looped into the public void run()
    I have another class which creates an instance of the above class (call it ClassB), and the main(String[] args) is in there.
    public static void main(String[] args)
              ClassA test = new ClassA();
              Thread thread = new Thread(test.getInstanceOfClassA());
              thread.start();
              while(true)
                           //I do not know what to put here
                   try
                        thread.sleep(100);
                   catch(InterruptedException iex)
         }However, the thread only calls run() once,(duh...) but I can't think of away to get it to run - sleep - run -sleep forever. Can someone help me?

    Hi, I have some code that needs to be constantly
    running, like while(true)
    //code here
    }However, the code just checks to see if the user has
    input anything (and then if the user has, it goes to
    do some other stuff) so I don't need it constantly
    running and hogging up 98% of the CPU. Where does the user input come from. Are you reading from an InputStream? If so, then your loop will be blocked anyway when reading from the InputStream until data is available. During that time, the loop will not consume processor cycles.
    public static void main(String[] args)
              ClassA test = new ClassA();
    Thread thread = new Thread(test.getInstanceOfClassA());I have never seen this idiom. If ClassA instanceof Runnable, you simply write new Thread(test).
              thread.start();
              while(true)
    //I do not know what to put
    do not know what to put here
                   try
                        thread.sleep(100);
                   catch(InterruptedException iex)
         }However, the thread only calls run() once,(duh...)Yeah, why would you want to call it more than once given that you have an infinite loop in ClassA.run()?
    Harald.
    Java Text Crunching: http://www.ebi.ac.uk/Rebholz-srv/whatizit/software

  • Problem with JFrame and busy/wait Cursor

    Hi -- I'm trying to set a JFrame's cursor to be the busy cursor,
    for the duration of some operation (usually just a few seconds).
    I can get it to work in some situations, but not others.
    Timing does seem to be an issue.
    There are thousands of posts on the BugParade, but
    in general Sun indicates this is not a bug. I just need
    a work-around.
    I've written a test program below to demonstrate the problem.
    I have the problem on Solaris, running with both J2SE 1.3 and 1.4.
    I have not tested on Windows yet.
    When you run the following code, three JFrames will be opened,
    each with the same 5 buttons. The first "F1" listens to its own
    buttons, and works fine. The other two (F2 and F3) listen
    to each other's buttons.
    The "BUSY" button simply sets the cursor on its listener
    to the busy cursor. The "DONE" button sets it to the
    default cursor. These work fine.
    The "SLEEP" button sets the cursor, sleeps for 3 seconds,
    and sets it back. This does not work.
    The "INVOKE LATER" button does the same thing,
    except is uses invokeLater to sleep and set the
    cursor back. This also does not work.
    The "DELAY" button sleeps for 3 seconds (giving you
    time to move the mouse into the other (listerner's)
    window, and then it behaves just like the "SLEEP"
    button. This works.
    Any ideas would be appreciated, thanks.
    -J
    import java.awt.BorderLayout;
    import java.awt.Cursor;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    public class BusyFrameTest implements ActionListener
    private static Cursor busy = Cursor.getPredefinedCursor (Cursor.WAIT_CURSOR);
    private static Cursor done = Cursor.getDefaultCursor();
    JFrame frame;
    JButton[] buttons;
    public BusyFrameTest (String title)
    frame = new JFrame (title);
    buttons = new JButton[5];
    buttons[0] = new JButton ("BUSY");
    buttons[1] = new JButton ("DONE");
    buttons[2] = new JButton ("SLEEP");
    buttons[3] = new JButton ("INVOKE LATER");
    buttons[4] = new JButton ("DELAY");
    JPanel buttonPanel = new JPanel();
    for (int i = 0; i < buttons.length; i++)
    buttonPanel.add (buttons);
    frame.getContentPane().add (buttonPanel);
    frame.pack();
    frame.setVisible (true);
    public void addListeners (ActionListener listener)
    for (int i = 0; i < buttons.length; i++)
    buttons[i].addActionListener (listener);
    public void actionPerformed (ActionEvent e)
    System.out.print (frame.getTitle() + ": " + e.getActionCommand());
    if (e.getActionCommand().equals ("BUSY"))
    frame.setCursor (busy);
    else if (e.getActionCommand().equals ("DONE"))
    frame.setCursor (done);
    else if (e.getActionCommand().equals ("SLEEP"))
    frame.setCursor (busy);
    try { Thread.sleep (3000); } catch (Exception ex) { }
    frame.setCursor (done);
    System.out.print (" finished");
    else if (e.getActionCommand().equals ("INVOKE LATER"))
    frame.setCursor (busy);
    SwingUtilities.invokeLater (thread);
    else if (e.getActionCommand().equals ("DELAY"))
    try { Thread.sleep (3000); } catch (Exception ex) { }
    frame.setCursor (busy);
    try { Thread.sleep (3000); } catch (Exception ex) { }
    frame.setCursor (done);
    System.out.print (" finished");
    System.out.println();
    Runnable thread = new Runnable()
    public void run()
    try { Thread.sleep (3000); } catch (Exception ex) { }
    frame.setCursor (done);
    System.out.println (" finished");
    public static void main (String[] args)
    BusyFrameTest f1 = new BusyFrameTest ("F1");
    f1.addListeners (f1);
    BusyFrameTest f2 = new BusyFrameTest ("F2");
    BusyFrameTest f3 = new BusyFrameTest ("F3");
    f2.addListeners (f3); // 2 listens to 3
    f3.addListeners (f2); // 3 listens to 2

    I've had the same problems with cursors and repaints in a swing application, and I was thinking of if I could use invokeLater, but I never got that far with it.
    I still believe you would need a thread for the time consuming task, and that invokeLater is something you only need to use in a thread different from the event thread.

  • Problem with DAQmx and Real Time PCI-7041/6040E.

    Problem with DAQmx and Real Time PCI-7041/6040E.
    I have a problem with the Real Time card PCI-7041/6040E, I think it is properly installed because my software run with the traditional NI-DAQ. When I try to use the new DAQmx to acquire one signal, Labview doesn't see any device for de DAQ card 6040E.
    Information, I work on Windows XP and LabView v7.0.0 (NIDAQ RT v7.0.0, NI-Serial RT v2.5.2, NI-VISA v3.0.1 and NI-Watchdog v2.0.0).
    Could Labview RT run with new DAQmx ?
    What can I do to use DAQmx with PCI-7041/6040E?
    Thanks for your help !

    Hello,
    I refer to your posts because i am using the PCI 7041/6040E card as
    well but without any success to make it work. The problem I have
    already described in the following thread:
    http://forums.ni.com/ni/board/message?board.id=170&message.id=120198
    Would be nice if you had a look on it, maybe you can help me. BTW, the
    thread starts with a problem of someone else, the difficulties I
    encountered are to be found a little bit to the bottom of the thread's
    page.
    Thank you!
    Dirk Völlger
    Darmstadt
    Message Edited by ratschnowski on 07-28-2005 07:14 AM

  • Problem with attachments and antivirus.scanners

    Hi!
    Problem is: Sending any attachment from Tiger (10.4.8) mail, all attachments are removed by a virus scanner at receiving end:
    This message was modified by F-Secure Anti-Virus E-Mail Scanning.
    Tried Windows friendly, text only, repair permissions, sending under other isp etc. no help.
    If this same message with same attachment is send from next mac with Panther, it is received ok.
    Receiving company is big and wont alter their virus-scanners and the problem clearly lies in Tiger.
    Any help welcome.
      Mac OS X (10.4.8)  

    The subject of your message should have been "Problems with attachments and F-Secure antivirus" since this is not a problem with all antivirus software, only with F-Secure.
    Check this thread for a possible temporary solution when sending attachments to those who use F-Secure.
    http://discussions.apple.com/thread.jspa?messageID=2837384&#2837384

Maybe you are looking for