java无限线程
我需要一个线程来检查 JAVA 桌面应用程序上的网络连接可用性。我有一个像这样的线程
class DataSyncThread extends Thread {
DataSyncThread() {
}
public void run() {
while(true){
try{
System.out.println("Checking for network");
InetAddress addr = InetAddress.getByName(host);
if(addr.isReachable(MIN_PRIORITY)){
syncData();
}
this.sleep(1000000);
}catch(Exception e){}
}
}
}
现在,当我在构造函数中调用它时,应用程序永远不会加载。当我查看控制台(我触发从其中加载 jar )线程工作时,它会在控制台中打印“检查网络”。
帮助赞赏
I need to have a thread which checks for network connection availability on a JAVA desktop app. I got a thread like this
class DataSyncThread extends Thread {
DataSyncThread() {
}
public void run() {
while(true){
try{
System.out.println("Checking for network");
InetAddress addr = InetAddress.getByName(host);
if(addr.isReachable(MIN_PRIORITY)){
syncData();
}
this.sleep(1000000);
}catch(Exception e){}
}
}
}
Now when I call this in the constructer the app never loads. when I look into the console (I trigger the jar to load from it) the thread work, it prints "Checking for network" in the console.
help appreciated
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我的猜测是,您正在做类似的事情:
这将同步运行
run()
方法。您应该调用start()
来创建一个单独的执行线程:我还建议实现
Runnable
而不是扩展Thread
- 或者很可能如果您希望定期执行,请使用Timer
代替。我希望你的真实代码也记录在你的 catch 块中......My guess is that you're doing something like:
That will run the
run()
method synchronously. You should be callingstart()
to create a separate thread of execution:I would also recommend implementing
Runnable
instead of extendingThread
- or quite possibly using aTimer
instead, given that you want periodic execution. I hope your real code has logging in your catch block, too...