Java中的工作线程

时间:2011-12-20 07:37:54

标签: java

我需要每分钟通过线程&读取表中的数据。然后执行某些动作。

我应该刚开始一个线程&任务完成后,将其置于睡眠模式1分钟。然后再次检查表格是否有任何数据,再次执行任务&睡了1分钟......

这是正确的做法吗?任何人都可以用Java为我提供一些示例代码吗?

谢谢!

4 个答案:

答案 0 :(得分:21)

通常,java.util.concurrent包中的Java 5扩展在这里是一个巨大的帮助。

您应该使用ScheduledThreadPoolExecutor。这是一个小的(untestet)示例:

class ToSomethingRunnable implements Runnable {
    void run() {
        // Add your customized code here to update the contents in the database.
    }
}

ScheduledThreadPoolExecutor executor = Executors.newScheduledThreadPool(1);
ScheduledFuture<?> future = executor.scheduleAtFixedRate(new ToSomethingRunnable(), 
     0, 1, TimeUnit.MINUTES); 

// at some point at the end
future.cancel();
executor.shutdown();

更新

使用Executor的一个好处是你可以添加许多不同时间间隔的重复任务,这些任务共享同一个线程池,这是一个简单但受控制的关闭。

答案 1 :(得分:1)

自己创建线程的另一种方法是使用ExcecutorService,其中 Executors.newScheduledThreadPool( 1 )创建一个大小为1的thred池 并且scheduleAtFixedRate有签名:scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit);

public class ScheduledDBPoll
{
  public static void main( String[] args )
  {
    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool( 1 );
    ScheduledFuture<?> sf = scheduler.scheduleAtFixedRate(
        new Runnable() {
          public void run() {
            pollDB();
          }
        },
        1,  60,TimeUnit.SECONDS );
  }
}

答案 2 :(得分:0)

你的方法很好。你可以继续你的方法。

此示例将帮助您完成任务:

class SimpleThread extends Thread {
   public SimpleThread(String str) {
    super(str);
   }
   public void run() {
    for (int i = 0; i < 10; i++) {
        System.out.println(i + " " + getName());
        try {
             // Add your customized code here to update the contents in the database.

            sleep((int)(Math.random() * 1000));

        } catch (InterruptedException e) {}
    }
    System.out.println("DONE! " + getName());
}
}

答案 3 :(得分:0)

&#34;我应该开始一个线程&amp;把它置于睡眠模式1分钟&#34; 即使你想要你想要使用传统的线程(不想使用执行器Fremework)也不要将SLEEP用于等待目的,因为它不会释放锁定及其阻塞操作。请在这里等待(超时)。

错误的方法 -

public synchronized void doSomething(long time)  throws InterruptedException {
  // ...
  Thread.sleep(time);
}

正确的方法

public synchronized void doSomething(long timeout) throws InterruptedException {
// ...
  while (<condition does not hold>) {
    wait(timeout); // Immediately releases the current monitor
  }
}

您可能需要查看链接https://www.securecoding.cert.org/confluence/display/java/LCK09-J.+Do+not+perform+operations+that+can+block+while+holding+a+lock

相关问题