Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the thread run only once?

I'm trying to track the position of the mouse cursor and thus need to use a thread to continue tracking it. My thread is running only once. I'm guessing that I have missed something along the way.

The code :

mousePosition class

import java.awt.MouseInfo;
import java.awt.Point;
import java.util.Timer;

public class mousePosition implements Runnable
{
    static Point mouseLocation = MouseInfo.getPointerInfo().getLocation();
    static Timer t = new Timer();
    int x,y = 0;


    public void run()
    {
        try
        {
                x = mouseLocation.x;
                y = mouseLocation.y;

                System.out.println("X:"+x+" Y:"+y+" at time "+System.currentTimeMillis());
        }

        catch(Exception e)
        {
            System.out.println("Exception caught : "+e);
        }

    }



}

main class

public class threadRunner
{
    public static void main(String[] args)
    {
        Thread t1 = new Thread(new mousePosition());

        t1.start();

    }

}

Thank you for any help. I know that this question was asked before but I am still struggling to make it work.

like image 549
alexeidebono Avatar asked Feb 02 '26 12:02

alexeidebono


2 Answers

The Thread's run() method will only run once. It would run much more if you did something like this:

public void run() {
  while(true) { // Or with a stop condition
    try {
            x = mouseLocation.x;
            y = mouseLocation.y;

            System.out.println("X:"+x+" Y:"+y+" at time "+System.currentTimeMillis());

    } catch(Exception e) {
        System.out.println("Exception caught : "+e);
    }
  }
}

Although I'm sure this while loop on a thread is expensive, speaking in computational cost, and there is a better practice using the Observer design pattern. An implementation and example of this good practice, is just precisely the MouseListener.

like image 198
waldyr.ar Avatar answered Feb 05 '26 00:02

waldyr.ar


When you start() a new Thread, the only thing that happens is that the Threads run() method is executed. Once the run() method is finished, the Thread dies.

To continually check the mouse position, you should probably start some kind of MouseListener instead, there is a nice tutorial here.

To learn more about threads, I recommend looking throw the Java Tutorials on the subject.

like image 31
Keppil Avatar answered Feb 05 '26 02:02

Keppil