欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java多线程并发executorservice(任务调度)类

程序员文章站 2024-02-16 19:51:46
复制代码 代码如下:package com.yao; import java.util.concurrent.executors;import java.util.con...

复制代码 代码如下:

package com.yao;

import java.util.concurrent.executors;
import java.util.concurrent.scheduledexecutorservice;
import java.util.concurrent.scheduledfuture;
import java.util.concurrent.timeunit;

/**
 * 以下是一个带方法的类,它设置了 scheduledexecutorservice ,2秒后,在 1 分钟内每 10 秒钟蜂鸣一次
 *
 * @author yaokj
 *
 */
class beepercontrol {
 private final scheduledexecutorservice scheduler = executors
   .newscheduledthreadpool(1);

 public void beepforanhour() {
  final runnable beeper = new runnable() {
   public void run() {
    system.out.println("beep");
   }
  };
  final scheduledfuture<?> beeperhandle = scheduler.scheduleatfixedrate(
    beeper, 2, 10, timeunit.seconds);
  scheduler.schedule(new runnable() {
   public void run() {
    beeperhandle.cancel(true);
    scheduler.shutdown();
   }
  }, 60, timeunit.seconds);

 }
}

public class scheduledexecutorservicedemo {

 public static void main(string[] args) {

  new beepercontrol().beepforanhour();
 }

}