您现在的位置:首页 >> 基础 >> Java编程 >> 内容

使用多线程执行任务的小型框架--Java学习网

时间:2016-8-8 12:38:44

  核心提示:1.[代码]当前需要执行的任务的元组?123456789101112import java.util.concurrent.Callable;import java.util.concurrent.F...

1. [代码]当前需要执行的任务的元组     

?
1
2
3
4
5
6
7
8
9
10
11
12
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
 
public class TaskItem<R, C extends Callable<R>> {
  public final Future<R> future;
  public final C task;
 
  public TaskItem(Future<R> future, C task) {
    this.future = future;
    this.task = task;
  }
}

2. [代码]任务管理器     

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
 
public class TaskManager<R, C extends Callable<R>> extends ArrayList<TaskItem<R, C>> {
  private ExecutorService exec = Executors.newSingleThreadExecutor();
 
  public void add(C task) {
    add(new TaskItem<>(exec.submit(task), task));
  }
 
  public List<R> getResults() {
    Iterator<TaskItem<R, C>> items = iterator();
    List<R> results = new ArrayList<>();
    while (items.hasNext()) {
      TaskItem<R, C> item = items.next();
      if (item.future.isDone()) {
        try {
          results.add(item.future.get());
        } catch (InterruptedException | ExecutionException e) {
          throw new RuntimeException(e);
        }
        items.remove();
      }
    }
    return results;
  }
 
  public List<String> purge() {
    Iterator<TaskItem<R, C>> items = iterator();
    List<String> results = new ArrayList<>();
    while (items.hasN, ext()) {
      TaskItem<R, C> item = items.next();
      if (!item.future.isDone()) {
        results.add("Cancelling " + item.task);
        item.future.cancel(true);
        items.remove();
      }
    }
    return results;
  }
}

3. [代码]任务类     

?
1
2
3
4
5
6
7
8
9
import java.util.concurrent.Callable;
 
public class CallableTask extends Task implements Callable<String> {
  @Override
  public String call() throws Exception {
    run();
    return "Return value of " + this;
  }
}

4. [代码]基任务类     

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import java.util.concurrent.TimeUnit;
 
public class Task implements Runnable {
  private static int counter = 0;
  private final int id = counter++;
 
  @Override
  public void run() {
    System.out.println(this + " started");
    try {
      TimeUnit.SECONDS.sleep(3);
    } catch (InterruptedException e) {
      System.out.println(this + " interrupted");
      return;
    }
    System.out.println(this + " completed");
  }
 
  @Override
  public String toString() {
    return "Task " + id;
  }
 
  public int id() {
    return id;
  }
}

5. [代码]程序入口     

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class InterruptableLongRunningCallable extends JFrame {
  private JButton
      b1 = new JButton("Start Long Running Task"),
      b2 = new JButton("End Long Running Task"),
      b3 = new JButton("Get Results");
  private TaskManager<String, CallableTask> manager = new TaskManager<>();
  public InterruptableLongRunningCallable() {
    b1.addActionListener(e -> {
      CallableTask task = new CallableTask();
      manager.add(task);
      System.out.println(task + " added to the queue");
    });
    b2.addActionListener(e -> {
      for (String result : manager.purge()) {
        System.out.println(result);
      }
    });
    b3.addActionListener(e -> {
      for (TaskItem<String, CallableTask> tt : manager) {
        tt.task.id();
      }
      for (String result : manager.getResults()) {
        System.out.println(result);
      }
    });
    setLayout(new FlowLayout());
    add(b1);
    add(b2);
    add(b3);
  }
 
  public static void main(String[] args) {
    run(new InterruptableLongRunningCallable(), 200, 150);
  }
}

Java免费学习   Java自学网 http://www.javalearns.com

关注微信号:javalearns   随时随地学Java

或扫一扫

随时随地学Java

作者:不详 来源:网络
    你是从哪里知道本网站的?
  • 网友介绍的
  • 百度搜索的
  • Google搜索的
  • 其它搜索过来的
  • 网址输错了进来的
  • 太忙了不记得了
共有评论 0相关评论
发表我的评论
  • 大名:
  • 内容:
  • java学习网(www.javalearns.com) © 2014 版权所有 All Rights Reserved.
  • Email:javalearns@163.com 站长QQ:1356121699 晋ICP备14003680号-3
  • java学习网部分内容来自网络或网友发布,如侵犯了您利益,请发邮件至:javalearns@126.com,我们尽快处理!
  • Java学习网
  • 网站统计
  • 晋公网安备 14042902000001号