一文搞懂Java创建线程的五种方法
题目描述
Java创建线程的几种方式
Java使用Thread类代表线程,所有线程对象都必须是Thread类或者其子类的实例。Java可以用以下5种方式来创建线程
- 继承Thread类创建线程;
- 实现Runnable接口创建线程;
- 实现Callable接口,通过FutureTask包装器来创建Thread线程;
- 使用ExecutorService、Callable(或者Runnable)、Future实现由返回结果的线程。
- 使用CompletableFuture类创建异步线程,且是据有返回结果的线程。 jdk8新支持的
实现:使用这5种方式创建线程,体验其中的妙处。
解题思路
继承Thread类创建线程
Thread类本质上是实现了Runnable接口的一个实例,代表一个线程的实例。启动线程的唯一方法就是通过Thread类的start()实例方法。start()方法是一个native方法,它将启动一个新线程,并执行run()方法。这种方式实现多线程很简单,通过自己的类直接extends Thread,并复写run()方法,就可以启动新线程并执行自己定义的run()方法。
实现Runnable接口创建线程
如果自己的类已经extends另一个类,就无法直接extends Thread,此时,可以实现一个Runnable接口
实现Callable接口,通过FutureTask包装器来创建Thread线程
实现一个Callable接口(它是一个具有返回值的)
使用ExecutorService、Callable(或者Runnable)、Future实现由返回结果的线程
Executors类,提供了一系列工厂方法用于创建线程池,返回的线程池都实现了ExecutorService接口:
Executors类,提供了一系列工厂方法用于创建线程池,返回的线程池都实现了ExecutorService接口:
//创建固定数目线程的线程池。
public static ExecutorService newFixedThreadPool(int nThreads) ;
//创建一个可缓存的线程池,调用execute 将重用以前构造的线程(如果线程可用)。如果现有线程没有可用的,则创建一个新线程并添加到池中。终止并从缓存中移除那些已有 60 秒钟未被使用的线程。
public static ExecutorService newCachedThreadPool();
//创建一个单线程化的Executor。
public static ExecutorService newSingleThreadExecutor();
//创建一个支持定时及周期性的任务执行的线程池,多数情况下可用来替代Timer类。
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize);
ExecutoreService提供了submit()方法,传递一个Callable,或Runnable,返回Future。如果Executor后台线程池还没有完成Callable的计算,这调用返回Future对象的get()方法,会阻塞直到计算完成。
使用CompletableFuture类创建异步线程,且是据有返回结果的线程
Future模式的缺点
Future虽然可以实现获取异步执行结果的需求,但是它没有提供通知的机制,我们无法得知Future什么时候完成。
要么使用阻塞,在future.get()的地方等待future返回的结果,这时又变成同步操作。要么使用isDone()轮询地判断Future是否完成,这样会耗费CPU的资源。
CompletableFuture 介绍
JDK1.8新加入的一个实现类CompletableFuture,实现了Future, CompletionStage两个接口。
CompletableFuture中4个异步执行任务静态方法:
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier) {
return asyncSupplyStage(asyncPool, supplier);
}
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier,Executor executor) {
return asyncSupplyStage(screenExecutor(executor), supplier);
}
public static CompletableFuture<Void> runAsync(Runnable runnable) {
return asyncRunStage(asyncPool, runnable);
}
public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor) {
return asyncRunStage(screenExecutor(executor), runnable);
}
其中supplyAsync用于有返回值的任务,runAsync则用于没有返回值的任务。Executor参数可以手动指定线程池,否则默认ForkJoinPool.commonPool()系统级公共线程池
代码详解
第一种 继承Thread类创建线程
package cn.xiaoxuzhu.daily;
import java.util.concurrent.CountDownLatch;
public class ThreadDemo1 extends Thread {
CountDownLatch countDownLatch;
public ThreadDemo1(CountDownLatch countDownLatch) {
this.countDownLatch = countDownLatch;
}
@Override
public void run() {
try {
Thread.sleep(2000);
System.out.println(Thread.currentThread().getName() + ":my thread ");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
countDownLatch.countDown();
}
}
public static void main(String[] args) {
// 第一种:使用extends Thread方式
CountDownLatch countDownLatch1 = new CountDownLatch(2);
for (int i = 0; i < 2; i++) {
ThreadDemo1 myThread1 = new ThreadDemo1(countDownLatch1);
myThread1.start();
}
try {
countDownLatch1.await();
System.out.println("thread complete...");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
第二种:实现Runnable接口创建线程
package cn.xiaoxuzhu.daily;
import java.util.concurrent.CountDownLatch;
public class ThreadDemo2 implements Runnable{
CountDownLatch countDownLatch;
public ThreadDemo2(CountDownLatch countDownLatch) {
this.countDownLatch = countDownLatch;
}
@Override
public void run() {
try {
Thread.sleep(2000);
System.out.println(Thread.currentThread().getName() + ":my runnable ");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
countDownLatch.countDown();
}
}
public static void main(String[] args) {
// 第二种:使用implements Runnable方式
CountDownLatch countDownLatch2 = new CountDownLatch(2);
ThreadDemo2 myRunnable = new ThreadDemo2(countDownLatch2);
for (int i = 0; i < 2; i++) {
new Thread(myRunnable).start();
}
try {
countDownLatch2.await();
System.out.println("runnable complete...");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
第三种:实现Callable接口,通过FutureTask包装器来创建Thread线程
计算1~100的叠加
package cn.xiaoxuzhu.daily;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class ThreadDemo3 implements Callable<Integer> {
public static void main(String[] args) {
ThreadDemo3 threadDemo03 = new ThreadDemo3();
//1、用futureTask接收结果
FutureTask<Integer> futureTask = new FutureTask<>(threadDemo03);
new Thread(futureTask).start();
//2、接收线程运算后的结果
try {
//futureTask.get();这个是堵塞性的等待
Integer sum = futureTask.get();
System.out.println("sum="+sum);
System.out.println("-------------------");
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = 0; i <101 ; i++) {
sum+=i;
}
return sum;
}
}
第四种:使用ExecutorService、Callable(或者Runnable)、Future实现返回结果的线程
package cn.xiaoxuzhu.daily;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class ThreadDemo4 {
static class MyCallable implements Callable<Integer> {
private CountDownLatch countDownLatch;
public MyCallable(CountDownLatch countDownLatch) {
this.countDownLatch = countDownLatch;
}
public Integer call() {
int sum = 0;
try {
for (int i = 0; i <= 100; i++) {
sum += i;
}
System.out.println("线程执行结果:"+sum);
} finally {
countDownLatch.countDown();
}
return sum;
}
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
// 第四种:使用使用线程池方式
// 接受返回参数
List<Future> resultItems2 = new ArrayList<Future>();
// 給线程池初始化5個线程
ExecutorService executorService = Executors.newFixedThreadPool(5);
CountDownLatch countDownLatch4 = new CountDownLatch(10);
for (int i = 0; i < 10; i++) {
MyCallable myCallable = new MyCallable(countDownLatch4);
Future result = executorService.submit(myCallable);
resultItems2.add(result);
}
// 等待线程池中分配的任务完成后才关闭(关闭之后不允许有新的线程加入,但是它并不会等待线程结束),
// 而executorService.shutdownNow();是立即关闭不管是否线程池中是否有其他未完成的线程。
executorService.shutdown();
try {
countDownLatch4.await();
Iterator<Future> iterator = resultItems2.iterator();
System.out.println("----------------------");
while (iterator.hasNext()) {
try {
System.out.println("线程返回结果:"+iterator.next().get());
} catch (ExecutionException e) {
e.printStackTrace();
}
}
System.out.println("callable complete...");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
第五种:使用ComletetableFuture类创建异步线程,且是据有返回结果的线程
package cn.xiaoxuzhu.daily;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
public class ThreadDemo5 {
@Test
public void completableFuture1(){
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("future1 finished!");
return "future1 finished!";
});
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
System.out.println("future2 finished!");
return "future2 finished!";
});
CompletableFuture<Void> future3 = CompletableFuture.allOf(future1, future2);
try {
future3.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println("future1: " + future1.isDone() + " future2: " + future2.isDone());
}
@Test
public void test01() throws Exception {
ExecutorService service = Executors.newFixedThreadPool(5);
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "xiaoxuzhu";
}, service);
CompletableFuture<Void> data = CompletableFuture.runAsync(() -> System.out.println("xiaoxuzhu"));
future.whenComplete((x,y)-> System.out.println("有延迟3秒:执行当前任务的线程继续执行:"+x+","+y)); //执行当前任务的线程继续执行
data.whenCompleteAsync((x,y)-> System.out.println("交给线程池另起线程执行:"+x+","+y)); // 交给线程池另起线程执行
future.exceptionally(Throwable::toString);
//System.out.println(future.get());
//第二个线程依赖第一个的结果
CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> 5).thenApply(x -> x);
CompletableFuture<Integer> future2 = future1.handleAsync((x, y) -> x + 2);
System.out.println(future2.get());//7
future2.thenAccept(System.out::println);
future2.thenRunAsync(()-> System.out.println("继续下一个任务"));
CompletableFuture<Integer> future3 = future1.thenCombine(future2, Integer::sum);
System.out.println(future3.get()); // 5+7=12
future1.thenAcceptBothAsync(future2,(x,y)-> System.out.println(x+","+y)); //5,7
CompletableFuture<Integer> future4 = future1.applyToEither(future2, x -> x);
System.out.println(future4.get()); //5
future1.acceptEither(future2, System.out::println);
future1.runAfterEither(future,()-> System.out.println("有一个完成了,我继续"));
future1.runAfterBoth(future,()-> System.out.println("都完成了,我继续"));
future1.thenComposeAsync(x->CompletableFuture.supplyAsync(()->x+1))
.thenComposeAsync(x->CompletableFuture.supplyAsync(()->x+2))
.thenCompose(x->CompletableFuture.runAsync(()-> System.out.println("流操作结果:"+x)));
TimeUnit.SECONDS.sleep(5);//主线程sleep,等待其他线程执行
}
}
以上就是一文搞懂Java创建线程的五种方法的详细内容,更多关于Java创建线程的资料请关注其它相关文章!
相关文章