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

java使用任务架构执行任务调度示例

程序员文章站 2024-02-16 22:09:34
复制代码 代码如下:package com.yao; import java.util.concurrent.callable;import java.util.conc...

复制代码 代码如下:

package com.yao;

import java.util.concurrent.callable;
import java.util.concurrent.executionexception;
import java.util.concurrent.executorservice;
import java.util.concurrent.executors;
import java.util.concurrent.future;
import java.util.concurrent.scheduledexecutorservice;
import java.util.concurrent.timeunit;

/**
 * 新的任务执行架构。
 * 在java 5.0之前启动一个任务是通过调用thread类的start()方法来实现的,
 * 任务的提于交和执行是同时进行的,如果你想对任务的执行进行调度,
 * 或是控制同时执行的线程数量就需要额外编写代码来完成。
 * 5.0里提供了一个新的任务执行架构使你可以轻松地调度和控制任务的执行,
 * 并且可以建立一个类似数据库连接池的线程池来执行任务。
 * 这个架构主要有三个接口和其相应的具体类组成。
 * 这三个接口是executor, executorservice和scheduledexecutorservice。
 * (1)executor接口:是用来执行runnable任务的,它只定义一个方法:
 * execute(runnable command):执行ruannable类型的任务
 * (2)executorservice:继承了executor的方法,并提供了执行callable任务和中止任务执行的服务,
 * 其定义的方法主要有:
 * submit(task):可用来提交callable或runnable任务,并返回代表此任务的future对象
 * invokeall(collection of tasks):批处理任务集合,并返回一个代表这些任务的future对象集合
 * shutdown():在完成已提交的任务后关闭服务,不再接受新任务
 * shutdownnow():停止所有正在执行的任务并关闭服务。
 * isterminated():测试是否所有任务都执行完毕了。
 * isshutdown():测试是否该executorservice已被关闭
 * (3)scheduledexecutorservice:继承executorservice,提供了按时间安排执行任务的功能、
 * schedule(task, initdelay): 安排所提交的callable或runnable任务在initdelay指定的时间后执行。
 * scheduleatfixedrate():安排所提交的runnable任务按指定的间隔重复执行
 * schedulewithfixeddelay():安排所提交的runnable任务在每次执行完后,等待delay所指定的时间后重复执行。
 *
 * 通过executors类来获得各种服务对象。
 * callable(runnable task): 将runnable的任务转化成callable的任务
 * newsinglethreadexecutor: 产生一个executorservice对象,这个对象只有一个线程可用来执行任务,若任务多于一个,任务将按先后顺序执行。
 * newcachedthreadpool(): 产生一个executorservice对象,这个对象带有一个线程池,线程池的大小会根据需要调整,线程执行完任务后返回线程池,供执行下一次任务使用。
 * newfixedthreadpool(int poolsize):产生一个executorservice对象,这个对象带有一个大小为poolsize的线程池,若任务数量大于poolsize,任务会被放在一个queue里顺序执行。
 * newsinglethreadscheduledexecutor:产生一个scheduledexecutorservice对象,这个对象的线程池大小为1,若任务多于一个,任务将按先后顺序执行。
 * newscheduledthreadpool(int poolsize): 产生一个scheduledexecutorservice对象,这个对象的线程池大小为poolsize,若任务数量大于poolsize,任务会在一个queue里等待执行
 */
public class executearch {

 /**
  * 该线程输出一行字符串
  */
 public static class mythread implements runnable {
  public void run() {
   system.out.println("task repeating. " + system.currenttimemillis());
   try {
    thread.sleep(1000);
   } catch (interruptedexception e) {
    system.out.println("task interrupted. "
      + system.currenttimemillis());
   }
  }
 }

 /**
  * 该callable结束另一个任务
  */
 public static class mycallable implements callable {
  private future future;

  public mycallable(future future) {
   this.future = future;
  }

  public string call() {
   system.out.println("to cancell task..."
     + +system.currenttimemillis());
   this.future.cancel(true);
   return "task cancelled!";
  }
 }

 /**
  * @param args
  * @throws executionexception
  * @throws interruptedexception
  */
 public static void main(string[] args) throws interruptedexception,
   executionexception {
  // 产生一个executorservice对象,这个对象带有一个线程池,线程池的大小会根据需要调整,
  // 线程执行完任务后返回线程池,供执行下一次任务使用。
  executorservice cachedservice = executors.newcachedthreadpool();
  future mythreadfuture = cachedservice.submit(new mythread());
  future mycallablefuture = cachedservice.submit(new mycallable(
    mythreadfuture));
  system.out.println(mycallablefuture.get());
  system.out.println("-----------------");

  // 将runnable任务转换成callable任务
  callable mythreadcallable = executors.callable(new mythread());
  future mythreadcallablefuture = cachedservice.submit(mythreadcallable);
  // 对于runnable任务,转换成callable任务后,也没有返回值
  system.out.println(mythreadcallablefuture.get());
  cachedservice.shutdownnow();
  system.out.println("-----------------");

  // 产生一个executorservice对象,这个对象带有一个大小为poolsize的线程池,
  // 若任务数量大于poolsize,任务会被放在一个queue里顺序执行
  executorservice fixedservice = executors.newfixedthreadpool(2);
  fixedservice.submit(new mythread());
  fixedservice.submit(new mythread());
  // 由于线程池大小为2,所以后面的任务必须等待前面的任务执行完后才能被执行。
  mythreadfuture = fixedservice.submit(new mythread());
  mycallablefuture = fixedservice.submit(new mycallable(mythreadfuture));
  system.out.println(mycallablefuture.get());
  fixedservice.shutdownnow();
  system.out.println("-----------------");

  // 产生一个scheduledexecutorservice对象,这个对象的线程池大小为poolsize,
  // 若任务数量大于poolsize,任务会在一个queue里等待执行
  scheduledexecutorservice fixedscheduledservice = executors
    .newscheduledthreadpool(2);
  // 新建任务1
  mythread task1 = new mythread();
  // 使用任务执行服务立即执行任务1,而且此后每隔2秒执行一次任务1。
  mythreadfuture = fixedscheduledservice.scheduleatfixedrate(task1, 0, 2,
    timeunit.seconds);
  // 新建任务2
  mycallable task2 = new mycallable(mythreadfuture);
  // 使用任务执行服务等待5秒后执行任务2,执行它后会将任务1关闭。
  mycallablefuture = fixedscheduledservice.schedule(task2, 5,
    timeunit.seconds);
  system.out.println(mycallablefuture.get());
  fixedscheduledservice.shutdownnow();
 }
}