正常状况下,每一个子线程完成各自的任务就能够结束了。不过有的时候,咱们但愿多个线程协同工做来完成某个任务,这时就涉及到了线程间通讯了。java
本文涉及到的知识点:thread.join(), object.wait(), object.notify(), CountdownLatch, CyclicBarrier, FutureTask, Callable 等。git
本文涉及代码:github
https://github.com/wingjay/HelloJava/blob/master/multi-thread/src/ForArticle.java数据结构
下面我从几个例子做为切入点来说解下 Java 里有哪些方法来实现线程间通讯。dom
假设有两个线程,一个是线程 A,另外一个是线程 B,两个线程分别依次打印 1-3 三个数字便可。咱们来看下代码:ide
1 private static void demo1() { 2 Thread A = new Thread(new Runnable() { 3 @Override 4 public void run() { 5 printNumber("A"); 6 } 7 }); 8 Thread B = new Thread(new Runnable() { 9 @Override 10 public void run() { 11 printNumber("B"); 12 } 13 }); 14 A.start(); 15 B.start(); 16 }
其中的 printNumber(String) 实现以下,用来依次打印 1, 2, 3 三个数字:spa
1 private static void printNumber(String threadName) { 2 int i=0; 3 while (i++ < 3) { 4 try { 5 Thread.sleep(100); 6 } catch (InterruptedException e) { 7 e.printStackTrace(); 8 } 9 System.out.println(threadName + "print:" + i); 10 } 11 }
这时咱们获得的结果是:线程
1 B print: 1 2 A print: 1 3 B print: 2 4 A print: 2 5 B print: 3 6 A print: 3
能够看到 A 和 B 是同时打印的。code
那么,若是咱们但愿 B 在 A 所有打印 完后再开始打印呢?咱们能够利用 thread.join() 方法,代码以下:对象
1 private static void demo2() { 2 Thread A = new Thread(new Runnable() { 3 @Override 4 public void run() { 5 printNumber("A"); 6 } 7 }); 8 Thread B = new Thread(new Runnable() { 9 @Override 10 public void run() { 11 System.out.println("B 开始等待 A"); 12 try { 13 A.join(); 14 } catch (InterruptedException e) { 15 e.printStackTrace(); 16 } 17 printNumber("B"); 18 } 19 }); 20 B.start(); 21 A.start(); 22 }
获得的结果以下:
1 B 开始等待 A 2 A print: 1 3 A print: 2 4 A print: 3 5 6 B print: 1 7 B print: 2 8 B print: 3
因此咱们能看到 A.join() 方法会让 B一直等待直到 A 运行完毕。
仍是上面那个例子,我如今但愿 A 在打印完 1 后,再让 B 打印 1, 2, 3,最后再回到 A 继续打印 2, 3。这种需求下,显然 Thread.join() 已经不能知足了。咱们须要更细粒度的锁来控制执行顺序。
这里,咱们能够利用 object.wait() 和 object.notify() 两个方法来实现。代码以下:
1 /** 2 * A 1, B 1, B 2, B 3, A 2, A 3 3 */ 4 private static void demo3() { 5 Object lock = new Object(); 6 Thread A = new Thread(new Runnable() { 7 @Override 8 public void run() { 9 synchronized (lock) { 10 System.out.println("A 1"); 11 try { 12 lock.wait(); 13 } catch (InterruptedException e) { 14 e.printStackTrace(); 15 } 16 System.out.println("A 2"); 17 System.out.println("A 3"); 18 } 19 } 20 }); 21 Thread B = new Thread(new Runnable() { 22 @Override 23 public void run() { 24 synchronized (lock) { 25 System.out.println("B 1"); 26 System.out.println("B 2"); 27 System.out.println("B 3"); 28 lock.notify(); 29 } 30 } 31 }); 32 A.start(); 33 B.start(); 34 }
打印结果以下:
1 A 1 2 A waiting… 3 4 B 1 5 B 2 6 B 3 7 A 2 8 A 3
正是咱们要的结果。
那么,这个过程发生了什么呢?
为了更好理解,我在上面的代码里加上 log 方便读者查看。
1 private static void demo3() { 2 Object lock = new Object(); 3 Thread A = new Thread(new Runnable() { 4 @Override 5 public void run() { 6 System.out.println("INFO: A 等待锁"); 7 synchronized (lock) { 8 System.out.println("INFO: A 获得了锁 lock"); 9 System.out.println("A 1"); 10 try { 11 System.out.println("INFO: A 准备进入等待状态,放弃锁 lock 的控制权"); 12 lock.wait(); 13 } catch (InterruptedException e) { 14 e.printStackTrace(); 15 } 16 System.out.println("INFO: 有人唤醒了 A, A 从新得到锁 lock"); 17 System.out.println("A 2"); 18 System.out.println("A 3"); 19 } 20 } 21 }); 22 Thread B = new Thread(new Runnable() { 23 @Override 24 public void run() { 25 System.out.println("INFO: B 等待锁"); 26 synchronized (lock) { 27 System.out.println("INFO: B 获得了锁 lock"); 28 System.out.println("B 1"); 29 System.out.println("B 2"); 30 System.out.println("B 3"); 31 System.out.println("INFO: B 打印完毕,调用 notify 方法"); 32 lock.notify(); 33 } 34 } 35 }); 36 A.start(); 37 B.start(); 38 }
打印结果以下:
1 INFO: A 等待锁 2 INFO: A 获得了锁 lock 3 A 1 4 INFO: A 准备进入等待状态,调用 lock.wait() 放弃锁 lock 的控制权 5 INFO: B 等待锁 6 INFO: B 获得了锁 lock 7 B 1 8 B 2 9 B 3 10 INFO: B 打印完毕,调用 lock.notify() 方法 11 INFO: 有人唤醒了 A, A 从新得到锁 lock 12 A 2 13 A 3
最开始咱们介绍了 thread.join(),可让一个线程等另外一个线程运行完毕后再继续执行,那咱们能够在 D 线程里依次 join A B C,不过这也就使得 A B C 必须依次执行,而咱们要的是这三者能同步运行。
或者说,咱们但愿达到的目的是:A B C 三个线程同时运行,各自独立运行完后通知 D;对 D 而言,只要 A B C 都运行完了,D 再开始运行。针对这种状况,咱们能够利用 CountdownLatch 来实现这类通讯方式。它的基本用法是:
实现代码以下:
1 private static void runDAfterABC() { 2 int worker = 3; 3 CountDownLatch countDownLatch = new CountDownLatch(worker); 4 new Thread(new Runnable() { 5 @Override 6 public void run() { 7 System.out.println("D is waiting for other three threads"); 8 try { 9 countDownLatch.await(); 10 System.out.println("All done, D starts working"); 11 } catch (InterruptedException e) { 12 e.printStackTrace(); 13 } 14 } 15 }).start(); 16 for (char threadName='A'; threadName <= 'C'; threadName++) { 17 final String tN = String.valueOf(threadName); 18 new Thread(new Runnable() { 19 @Override 20 public void run() { 21 System.out.println(tN + "is working"); 22 try { 23 Thread.sleep(100); 24 } catch (Exception e) { 25 e.printStackTrace(); 26 } 27 System.out.println(tN + "finished"); 28 countDownLatch.countDown(); 29 } 30 }).start(); 31 } 32 }
下面是运行结果:
1 D is waiting for other three threads 2 A is working 3 B is working 4 C is working 5 6 A finished 7 C finished 8 B finished 9 All done, D starts working
其实简单点来讲,CountDownLatch 就是一个倒计数器,咱们把初始计数值设置为3,当 D 运行时,先调用 countDownLatch.await() 检查计数器值是否为 0,若不为 0 则保持等待状态;当A B C 各自运行完后都会利用countDownLatch.countDown(),将倒计数器减 1,当三个都运行完后,计数器被减至 0;此时当即触发 D 的 await() 运行结束,继续向下执行。
所以,CountDownLatch 适用于一个线程去等待多个线程的状况。
上面是一个形象的比喻,针对 线程 A B C 各自开始准备,直到三者都准备完毕,而后再同时运行 。也就是要实现一种 线程之间互相等待 的效果,那应该怎么来实现呢?
上面的 CountDownLatch 能够用来倒计数,但当计数完毕,只有一个线程的 await() 会获得响应,没法让多个线程同时触发。
为了实现线程间互相等待这种需求,咱们能够利用 CyclicBarrier 数据结构,它的基本用法是:
实现代码以下,设想有三个跑步运动员,各自准备好后等待其余人,所有准备好后才开始跑:
1 private static void runABCWhenAllReady() { 2 int runner = 3; 3 CyclicBarrier cyclicBarrier = new CyclicBarrier(runner); 4 final Random random = new Random(); 5 for (char runnerName='A'; runnerName <= 'C'; runnerName++) { 6 final String rN = String.valueOf(runnerName); 7 new Thread(new Runnable() { 8 @Override 9 public void run() { 10 long prepareTime = random.nextInt(10000) + 100; 11 System.out.println(rN + "is preparing for time:" + prepareTime); 12 try { 13 Thread.sleep(prepareTime); 14 } catch (Exception e) { 15 e.printStackTrace(); 16 } 17 try { 18 System.out.println(rN + "is prepared, waiting for others"); 19 cyclicBarrier.await(); // 当前运动员准备完毕,等待别人准备好 20 } catch (InterruptedException e) { 21 e.printStackTrace(); 22 } catch (BrokenBarrierException e) { 23 e.printStackTrace(); 24 } 25 System.out.println(rN + "starts running"); // 全部运动员都准备好了,一块儿开始跑 26 } 27 }).start(); 28 } 29 }
打印的结果以下:
1 A is preparing for time: 4131 2 B is preparing for time: 6349 3 C is preparing for time: 8206 4 5 A is prepared, waiting for others 6 7 B is prepared, waiting for others 8 9 C is prepared, waiting for others 10 11 C starts running 12 A starts running 13 B starts running
实际的开发中,咱们常常要建立子线程来作一些耗时任务,而后把任务执行结果回传给主线程使用,这种状况在 Java 里要如何实现呢?
回顾线程的建立,咱们通常会把 Runnable 对象传给 Thread 去执行。Runnable定义以下:
1 public interface Runnable { 2 public abstract void run(); 3 }
能够看到 run() 在执行完后不会返回任何结果。那若是但愿返回结果呢?这里能够利用另外一个相似的接口类 Callable:
1 @FunctionalInterface 2 public interface Callable<V> { 3 /** 4 * Computes a result, or throws an exception if unable to do so. 5 * 6 * @return computed result 7 * @throws Exception if unable to compute a result 8 */ 9 V call() throws Exception; 10 }
能够看出 Callable 最大区别就是返回范型 V 结果。
那么下一个问题就是,如何把子线程的结果回传回来呢?在 Java 里,有一个类是配合 Callable 使用的:FutureTask,不过注意,它获取结果的 get 方法会阻塞主线程。
举例,咱们想让子线程去计算从 1 加到 100,并把算出的结果返回到主线程。
1 private static void doTaskWithResultInWorker() { 2 Callable<Integer> callable = new Callable<Integer>() { 3 @Override 4 public Integer call() throws Exception { 5 System.out.println("Task starts"); 6 Thread.sleep(1000); 7 int result = 0; 8 for (int i=0; i<=100; i++) { 9 result += i; 10 } 11 System.out.println("Task finished and return result"); 12 return result; 13 } 14 }; 15 FutureTask<Integer> futureTask = new FutureTask<>(callable); 16 new Thread(futureTask).start(); 17 try { 18 System.out.println("Before futureTask.get()"); 19 System.out.println("Result:" + futureTask.get()); 20 System.out.println("After futureTask.get()"); 21 } catch (InterruptedException e) { 22 e.printStackTrace(); 23 } catch (ExecutionException e) { 24 e.printStackTrace(); 25 } 26 }
打印结果以下:
1 Before futureTask.get() 2 3 Task starts 4 Task finished and return result 5 6 Result: 5050 7 After futureTask.get()
能够看到,主线程调用 futureTask.get() 方法时阻塞主线程;而后 Callable 内部开始执行,并返回运算结果;此时 futureTask.get() 获得结果,主线程恢复运行。
这里咱们能够学到,经过 FutureTask 和 Callable 能够直接在主线程得到子线程的运算结果,只不过须要阻塞主线程。固然,若是不但愿阻塞主线程,能够考虑利用 ExecutorService,把 FutureTask 放到线程池去管理执行。