0

我写了以下代码。我希望当控制变为 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());
        }

    }
}
4

2 回答 2

1

尽管这不是安排重复任务的首选方式,但您可以通过捕获Throwable而不是明确的异常列表来修复它。这样,您将确保抓住理论上可以抛出的任何东西。请务必打印整个异常堆栈跟踪,而不仅仅是消息。

当您修复捕获时,您将需要另外修复清理逻辑:将close语句放入finally. 更好的是,重写您的代码以使用自动资源管理。语法是try (Statement stmt = conn.createStatement()) { ... }.

安排重复任务的正确方法是使用 Executors:

final ScheduledExecutorService sched = Executors.newSingleThreadScheduledExecutor();
sched.scheduleWithFixedDelay(task, 0, wTIME, TimeUnit.MILLISECONDS);
于 2012-10-12T20:09:46.517 回答
0

你可以写

catch(Exception e) 

而不是你写的。它将捕获所有异常。

于 2012-10-12T20:17:59.547 回答