1、Java多线程-创建线程

1、使用Runnable接口
  Runnable是执行工作的独立任务,不返回任何值
  a.定义任务

 1 /**
 2  * Runnable接口,实现一个简单的线程
 3  */
 4 public class LiftOff implements Runnable {
 5     protected int countDown =10; // Default
 6     private static int taskCount  = 0;
 7     private final int id = taskCount++;
 8     
 9     public LiftOff() {
10     }
11     
12     public LiftOff(int countDown) {
13         this.countDown = countDown;
14     }
15     
16     public String status() {
17         return "#" + id + "(" + (countDown > 0 ? countDown : "Liftoff!")
18                 + "), ";
19     }
20     
21     @Override
22     public void run() {
23         while (countDown-- > 0) {
24             System.out.println(status());
25             Thread.yield();
26         }
27     }
28 }

b.任务多线程调用:

 1 /**
 2  * 启动多个线程,结果随机
 3  */
 4 public class MoreBasicThreads {
 5     public static void main(String[] args) {
 6         // 循环启动多个线程,线程调度器会自动分发线程,打印的结果有随机性
 7         for (int i = 0; i < 5; i++)
 8             //调试多线程程序,可以只启动一个线程查看结果
 9             new Thread(new LiftOff()).start();
10         System.out.println("Waiting for LiftOff");
11     }
12 }

2、使用Executor管理异步任务(綫程池)
  newCachedThreadPool():由系统控制线程的创建与回收
  newFixedThreadPool(int n):指定预先分配线程的数量
  newSingleThreadExecutor():任何时刻在任何线程中都只有唯一的任务在运行

 1 /**
 2  * newCachedThreadPool 不指定大小的线程池
 3  */
 4 public class CachedThreadPool {
 5     public static void main(String[] args) {
 6         // newCachedThreadPool()
 7         // 通常会创建与所需数量相同的线程,在回收旧线程时会停止创建新线程
 8         ExecutorService exec = Executors.newCachedThreadPool();
 9         for (int i = 0; i < 5; i++)
10             exec.execute(new LiftOff());
11         exec.shutdown();
12     }
13 }
14 /**
15  * newFixedThreadPool 创建指定大小的线程池
16  */
17 public class FixedThreadPool {
18     public static void main(String[] args) {
19         // Constructor argument is number of threads:
20         ExecutorService exec = Executors.newFixedThreadPool(3);
21         for (int i = 0; i < 5; i++)
22             exec.execute(new LiftOff());
23         exec.shutdown();
24     }
25 }
26 /**
27  * newSingleThreadExecutor 只创建一个线程,实际有用处P657
28  */
29 public class SingleThreadExecutor {
30     public static void main(String[] args) {
31         ExecutorService exec = Executors.newSingleThreadExecutor();
32         for (int i = 0; i < 5; i++)
33             exec.execute(new LiftOff());
34         exec.shutdown();
35     }
36 }

3、Callable接口,接受多线程任务的返回值
  Callable<T>,泛型T定义返回数据的类型

 1 /**
 2  * Callable<T>接口,任务完成,返回返回值
 3  */
 4 public class MyTaskWithResult implements Callable<String> {
 5     private int id;
 6     
 7     public MyTaskWithResult(int id) {
 8         super();
 9         this.id = id;
10     }
11     
12     /*
13      * @see java.util.concurrent.Callable#call()
14      */
15     @Override
16     public String call() throws Exception {
17         return "result of MyTaskWithResult : " + id;
18     }
19 }
20  * 获取并处理线程返回值
21  */
22 public class MycallableDemo {
23     
24     /**
25      * @param args
26      */
27     public static void main(String[] args) {
28         ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
29         List<Future<String>> results = new ArrayList<>();
30         for (int i = 0; i < 10; i++) {
31             //必须使用ExecutorService.submit()调用
32             //Callable<T>指定返回值的类型,submit()方法产生Future对象
33             Future<String> result = cachedThreadPool
34                     .submit(new MyTaskWithResult(i));
35             results.add(result);
36         }
37         
38         for (Future<String> fs : results) {
39             try {
40                 //使用get(),获取返回结果;如果返回值未准备好,get()将阻塞,直至结果准备就绪
41                 //可以使用isDone()方法查询Future是否已经完成
42                 String taskResult = fs.get();
43                 System.out.println(taskResult);
44             } catch (InterruptedException | ExecutionException e) {
45                 e.printStackTrace();
46             } finally {
47                 cachedThreadPool.shutdown();
48             }
49         }
50     }
51 }

猜你喜欢

转载自www.cnblogs.com/6xiong/p/12005592.html