[关闭]
@xmruibi 2015-03-10T01:09:29.000000Z 字数 1825 阅读 679

Concurrency Knowledge #1

concurrency_programing


  1. package main;
  2. import java.util.ArrayList;
  3. import java.util.concurrent.Callable;
  4. import java.util.concurrent.ExecutionException;
  5. import java.util.concurrent.ExecutorService;
  6. import java.util.concurrent.Executors;
  7. import java.util.concurrent.Future;
  8. public class ExecutorTest {
  9. public static void main(String[] args) {
  10. // different executor types:
  11. ExecutorService execCached = Executors.newCachedThreadPool();
  12. ExecutorService execFixed = Executors.newFixedThreadPool(5);
  13. ExecutorService execSingle = Executors.newSingleThreadExecutor();
  14. // execute runnable object
  15. //for (int i = 0; i < 5; i++)
  16. // execCached.execute(new ExecRunObject(5));
  17. // execFixed.execute(new ExecRunObject(5));
  18. // execSingle.execute(new ExecRunObject(5));
  19. //execCached.shutdown();
  20. /** The following example is for callable interface implementation **/
  21. ExecutorService execCall = Executors.newCachedThreadPool();
  22. // exec submit produce Future object
  23. ArrayList<Future<String>> res = new ArrayList<Future<String>>();
  24. for (int i = 0; i < 5; i++)
  25. res.add(execCall.submit(new ExecCallObject(i)));
  26. for (Future f : res)
  27. try {
  28. System.out.println(f.get());
  29. } catch (InterruptedException e) {
  30. e.printStackTrace();
  31. } catch (ExecutionException e) {
  32. e.printStackTrace();
  33. }finally{
  34. execCall.shutdown();
  35. }
  36. }
  37. }
  38. // implements runnable interface
  39. class ExecRunObject implements Runnable {
  40. protected int countDown = 10;
  41. private static int taskCount = 0;
  42. private final int id = taskCount++;
  43. public ExecRunObject(int countDown) {
  44. this.countDown = countDown;
  45. }
  46. public String status() {
  47. return "#" + id + "(" + (countDown > 0 ? countDown : "LiftOff") + ")";
  48. }
  49. @Override
  50. public void run() {
  51. while (countDown-- > 0) {
  52. System.out.print(status());
  53. Thread.yield();
  54. }
  55. }
  56. }
  57. // implements callable interface, in order to acquire return value from tasks
  58. class ExecCallObject implements Callable<String> {
  59. private int id;
  60. public ExecCallObject(int id) {
  61. this.id = id;
  62. }
  63. @Override
  64. public String call() throws Exception {
  65. // TODO Auto-generated method stub
  66. return "result of Task" + id;
  67. }
  68. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注