Why does the thread run only once?
java, multithreading
Solution
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.
Problem
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.