1 场景
多线程有两种应用场景:纯异步场景,与“同步”场景。
其中,
- 纯异步场景
即线程A顺序执行的程序中,添加了线程B处理某个任务,线程A优先返回结果,让调用者可以快速拿到结果,不至于线程A耗时过长而出现阻塞,线程B在返回结果后继续执行任务(可能会出现执行失败,而无法直接告知调用者,需要引入补偿机制),不影响结果的返回,即异步处理。 - “同步”场景
即线程执行的任务具有返回值,并且需要拿到当前的返回值继续进行执行,使用Future作为返回的类型,此时,多线程的异步已经不是异步执行,而是“同步”执行,因为需要等待线程执行的结果。
2 Test
2.1 同步
package thread;
import java.util.concurrent.*;
import java.util.logging.Logger;
import static common.constant.DigitalConstant.*;
/**
* ThreadPoolExecutor测试.
*
* @author xindaqi
* @date 2021-04-28 17:58
*/
public class ThreadPoolExecutorTestOne {
private static Logger logger = Logger.getLogger("ThreadPoolExecutorTestOne");
/**
* 有返回值测试.
*
* @return
* @throws InterruptedException
*/
private static String testWithReturn() throws InterruptedException {
logger.info("当前线程:" + Thread.currentThread().getName());
Thread.sleep(FIVE*THOUSAND_L);
return Thread.currentThread().getName();
}
/**
* 无返回值测试.
*
* @return
* @throws InterruptedException
*/
private static String testWithoutReturn() throws InterruptedException {
logger.info("当前线程:" + Thread.currentThread().getName());
Thread.sleep(FIVE*THOUSAND_L);
return Thread.currentThread().getName();
}
public static void AsynchronizedTest(ExecutorService executorService, Integer flag) {
switch(flag) {
case ONE:
try {
Future<String> future = executorService.submit(() -> testWithReturn());
logger.info("Future content:" + future.get());
logger.info("我有返回值,是同步");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (ExecutionException e) {
throw new RuntimeException(e);
} finally {
executorService.shutdown();
break;
}
case TWO:
try {
executorService.submit(() -> testWithoutReturn());
logger.info("我没有返回值,是异步");
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
executorService.shutdown();
break;
}
default:
logger.info("不匹配");
}
}
public static void main(String[] args) {
ExecutorService threadPoolExecutor = new ThreadPoolExecutor(
THREE,
FIVE,
THOUSAND_L,
TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(TWO),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy());
AsynchronizedTest(threadPoolExecutor, ONE);
}
}
- 结果
四月 28, 2021 6:56:23 下午 thread.ThreadPoolExecutorTestOne testWithReturn
信息: 当前线程:pool-1-thread-1
四月 28, 2021 6:56:28 下午 thread.ThreadPoolExecutorTestOne AsynchronizedTest
信息: Future content:pool-1-thread-1
四月 28, 2021 6:56:28 下午 thread.ThreadPoolExecutorTestOne AsynchronizedTest
信息: 我有返回值,是同步 - 分析
由运行结果可知,使用Future获取线程执行结果,是顺序执行,同步而非异步。
2.2 异步
package thread;
import java.util.concurrent.*;
import java.util.logging.Logger;
import static common.constant.DigitalConstant.*;
/**
* ThreadPoolExecutor测试.
*
* @author xindaqi
* @date 2021-04-28 17:58
*/
public class ThreadPoolExecutorTestOne {
private static Logger logger = Logger.getLogger("ThreadPoolExecutorTestOne");
/**
* 有返回值测试.
*
* @return
* @throws InterruptedException
*/
private static String testWithReturn() throws InterruptedException {
logger.info("当前线程:" + Thread.currentThread().getName());
Thread.sleep(FIVE*THOUSAND_L);
return Thread.currentThread().getName();
}
/**
* 无返回值测试.
*
* @return
* @throws InterruptedException
*/
private static String testWithoutReturn() throws InterruptedException {
logger.info("当前线程:" + Thread.currentThread().getName());
Thread.sleep(FIVE*THOUSAND_L);
return Thread.currentThread().getName();
}
public static void AsynchronizedTest(ExecutorService executorService, Integer flag) {
switch(flag) {
case ONE:
try {
Future<String> future = executorService.submit(() -> testWithReturn());
logger.info("Future content:" + future.get());
logger.info("我有返回值,是同步");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (ExecutionException e) {
throw new RuntimeException(e);
} finally {
executorService.shutdown();
break;
}
case TWO:
try {
executorService.submit(() -> testWithoutReturn());
logger.info("我没有返回值,是异步");
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
executorService.shutdown();
break;
}
default:
logger.info("不匹配");
}
}
public static void main(String[] args) {
ExecutorService threadPoolExecutor = new ThreadPoolExecutor(
THREE,
FIVE,
THOUSAND_L,
TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(TWO),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy());
AsynchronizedTest(threadPoolExecutor, TWO);
}
}
- 结果
四月 28, 2021 6:52:59 下午 thread.ThreadPoolExecutorTestOne AsynchronizedTest
信息: 我没有返回值,是异步
四月 28, 2021 6:52:59 下午 thread.ThreadPoolExecutorTestOne testWithoutReturn
信息: 当前线程:pool-1-thread-1 - 分析
由运行结果可知,线程执行结果,是异步,先执行第二个结果: 我没有返回值,是异步,然后异步执行线程中的另一个任务。