我写了以下代码。我希望当控制变为 1 时无限循环应该停止。否则,它会在定期的一段时间后继续更新 SQL 数据库。某种异常导致线程终止。我无法弄清楚。有人可以帮忙吗?
public void run()
{
while(true)
{
System.out.println("I am working t asfbjakhbfjabf");
synchronized(lock)
{
if(control==1)
{
return;
}
}
try
{
Thread.sleep(wTIME);
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
String st="SELECT count FROM ThreadResults WHERE ThreadNo = "
+t;
Statement stmt = conn.createStatement();
stmt.execute(st);
ResultSet resultSet = stmt.getResultSet();
boolean b=resultSet.next();
synchronized(WebCrawler.seed.lock6)
{
float t1=(System.currentTimeMillis()-time)/60000;
if(b)
{
String s2="UPDATE ThreadResults SET count = "+WebCrawler.seed.count+", time = "+t1+" WHERE ThreadNo = "+t;
System.out.println("updated count");
stmt.executeUpdate(s2);
}
else
{
String s1="INSERT ThreadResults VALUES("+t+" ,"+WebCrawler.seed.count+" ,"+t1+")";
System.out.println("inserting count");
stmt.executeUpdate(s1);
}
}
resultSet.close();
conn.close();
}
catch(InterruptedException | ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException c)
{
System.out.println("caught in thread resilt updation "+ c.getMessage());
}
}
}
最佳答案
虽然这不是安排重复任务的首选方法,但您可以通过捕获 Throwable
而不是显式异常列表来修复它。这样你就可以确保你捕获了理论上可以扔出的任何东西。请务必打印整个异常堆栈跟踪,而不仅仅是消息。
修复捕获时,您需要额外修复清理逻辑:将 close
语句放入 finally
中。更好的是,重写代码以使用自动资源管理。语法为 try (Statement stmt = conn.createStatement()) { ... }
。
安排重复任务的正确方法是使用执行器:
final ScheduledExecutorService sched = Executors.newSingleThreadScheduledExecutor();
sched.scheduleWithFixedDelay(task, 0, wTIME, TimeUnit.MILLISECONDS);
关于java - 无限循环的线程在捕获一些异常后停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12866351/