使用Java多线程编程时经常遇到主线程需要等待子线程执行完成以后才能继续执行,那么接下来介绍一种简单的方式使主线程等待. java.util.concurrent.CountDownLatch 使用countDownLatch.await()方法非常简单的完成主线程的等待: public class ThreadWait { public static void main(String[] args) throws InterruptedException { int threadNumber
初识Callable and Future 在编码时,我们可以通过继承Thread或是实现Runnable接口来创建线程,但是这两种方式都存在一个缺陷:在执行完任务之后无法获取执行结果.如果需要获取执行结果,就必须通过共享变量或者使用线程通信的方式来达到目的.Java5提供了Callable和Future,通过它们可以在任务执行完毕之后得到任务执行结果. Callable and Future源码: (1)Callable接口: public interface Callable<V> { V
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Test { public static void main(String args[]) throws InterruptedException { ExecutorService exe = Executors.newFixedThreadPool(3); for (int i = 1; i <= 5
一.join() Thread中的join()方法就是同步,它使得线程之间由并行执行变为串行执行. public class MyJoinTest { public static void main(String[] args) { Vector<Thread> threadVector = new Vector<Thread>(); for (int i = 0;i<5;i++){ Thread childThread = new Thread(new Runnable()
题目:子线程执行10次后,主线程再运行5次,这样交替执行三遍 代码如下: package com.itheima.gan; /** * 子线程执行10次后,主线程再运行5次,这样交替执行三遍 * @author 12428 * */ public class Test { public static void main(String[] args) { final Bussiness bussiness=new Bussiness(); //创建一个子线程,run方法里面子线程执行3变 new