为什么线程只运行一次?
我想跟踪鼠标光标的位置,因此需要使用一个线程来继续跟踪它。我的线程只运行一次。我猜测我错过了一些东西。为什么线程只运行一次?
代码:
mousePosition类
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);
}
}
}
主类
public class threadRunner
{
public static void main(String[] args)
{
Thread t1 = new Thread(new mousePosition());
t1.start();
}
}
感谢您的任何帮助。我知道这个问题以前曾被问过,但我仍然在努力使其工作。
线程的run()
方法将只运行一次。虽然我敢肯定,在一个线程这个while循环是昂贵的,在计算成本上讲
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);
}
}
}
,并且存在使用Observer design pattern一个更好的做法:它会跑得更如果你做了这样的事情。这个良好实践的实施和示例恰恰就是MouseListener。
当你start()
一个新的Thread
,唯一发生的是执行Thread
s run()
方法。一旦run()
方法完成,Thread
死亡。
要不断地检查鼠标的位置,你应该开始某种MouseListener
相反,有一个很好的教程here。
要了解有关线索的更多信息,我建议您看看投掷Java Tutorials on the subject。
啊好吧,这是有道理的..所以明智地循环尝试代码在运行?因为当我这样做时,它给了我相同鼠标位置的答案,这也是合理的。我认为它是一个问题,在哪里放置循环 – alexeidebono 2012-07-20 11:45:56
我会看看这些链接谢谢! – alexeidebono 2012-07-20 11:47:17
@alexeidebono:由于您只在创建线程时检查鼠标位置,因此循环在此处不会执行太多操作。查看一些有用的阅读我的链接。 – Keppil 2012-07-20 11:47:31
做到这一点:
public void run()
{
try
{
boolean mouseTracked = false;
while(!mouseTracked){
x = mouseLocation.x;
y = mouseLocation.y;
System.out.println("X:"+x+" Y:"+y+" at time "+System.currentTimeMillis());
mouseTracked = true; //do this when mouse tracked..
}
}
catch(Exception e)
{
System.out.println("Exception caught : "+e);
}
}
这将继续追踪鼠标,直到你设置mouseTracked为true,设置mouseTracked到真实的,你会在比赛中状态
做改变你的类像这样
import java.awt.MouseInfo;
import java.awt.Point;
import java.util.Timer;
public class MousePosition implements Runnable
{
static Point mouseLocation = null;
static Timer t = new Timer();
int x,y = 0;
public void run()
{
while(true){
try
{
mouseLocation= MouseInfo.getPointerInfo().getLocation();
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);
}
}
}
}
这里读鼠标位置每隔50ms
01简单的方法
由于没有循环,并且您不使用计时器,所以'run'方法只运行一次是有道理的。 – assylias 2012-07-20 11:42:00
你为什么不在你的线程中使用你的计时器?线程的'run()'方法将在执行代码并结束您的线程后始终返回! – 2012-07-20 11:45:14
你通常在run方法中有一些while语句,以保持线程正常运行,而且经常是真的 – 2012-07-20 11:46:40