如何初始化线程进入睡眠状态

时间:2014-07-16 10:03:19

标签: java multithreading concurrency runnable

我正在尝试编写一种每小时ping一次数据库的方法。在这样做的过程中我遇到了一些困难,因为它可能没有被初始化

private void pingServer(){
    final Thread serverPing = new Thread(new Runnable() {
        @Override
        public void run() {
            Connection conn = null;
            try {
                conn = source.getConnection();
                while(conn.isValid(3600)){
                    //no need to do anything as conn.isValid does the ping
                    serverPing.sleep(3600000);
                }
            } catch (SQLException | InterruptedException e) {}
            finally{
                closeConnection(conn);
            }
        }
    });
    serverPing.setDaemon(true);
    serverPing.start();
}

如何修改此代码以正确初始化?

由于

2 个答案:

答案 0 :(得分:3)

要睡觉,只需使用Thread.sleep(3600000);

然而,你应该使用ScheduledExecutorService来完成这类任务:

ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
ses.scheduleAtFixedRate(new Runnable() {
    @Override
    public void run() {
        try(Connection conn = source.getConnection()){
            if(!conn.isValid(3600)){
                // do something if the connection is invalid
            }
        }
    }
}, 0, 1, TimeUnit.HOURS);

答案 1 :(得分:0)

只需使用Thread.sleep(TIME_GAP);来休眠当前线程。

实施例

    while(conn.isValid(3600)){
       try {
        Thread.sleep(3600000);
       } catch (InterruptedException e) {
        e.printStackTrace();
       }         
    }