Java实现多线程的方式
Java实现多线程的方式有4种:
继承Thread方法、实现Runnable接口、实现Callable接口并通过FutureTask创建线程、使用ExecutorService。
其中,前两种线程执行结果没有返回值,后两种是有返回值的。
1、继承Thread方法
Thread类实现了Runnable接口,通过调用start()方法启动线程。
这种方式实现多线程,通过继承Thread类,并在复写的run方法中实现业务逻辑。
// Thread测试用例
public class MyThread extends Thread{
@Override
public void run() {
System.out.println("local logic for Thread test.");
}
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
}
}
2、实现Runnable接口
这种方式通过直接实现Runnable接口,由于业务类需要借助于Thread类的start方法等功能,因此,通过实例化的Thread类,来进行业务逻辑调用(调用start方法后会执行run方法)。
// Runnable 测试用例
public class MyThread2 implements Runnable {
@Override
public void run() {
System.out.println("local logic for Runnable test.");
}
public static void main(String[] args) {
MyThread2 myThread = new MyThread2();
Thread thread = new Thread(myThread);
thread.start();
}
}
3、实现Callable接口并通过FutureTask创建线程
Callable和Runnable的区别主要在于,前者有返回值。
FutureTask实现了RunnableFuture接口,而RunnableFuture接口继承了Runnable和Future接口,通过Future接口可以得到任务执行的一些信息,Future接口介绍如下:
public interface Future<V> {
//取消任务,如果任务正在运行的,mayInterruptIfRunning为true时,表明这个任务会被打断的,并返回true;
//为false时,会等待这个任务执行完,返回true;若任务还没执行,取消任务后返回true,如任务执行完,返回false
boolean cancel(boolean mayInterruptIfRunning);
//判断任务是否被取消了,正常执行完不算被取消
boolean isCancelled();
//判断任务是否已经执行完成,任务取消或发生异常也算是完成,返回true
boolean isDone();
//获取任务返回结果,如果任务没有执行完成则等待完成将结果返回,如果获取的过程中发生异常就抛出异常,
//比如中断就会抛出InterruptedException异常等异常
V get() throws InterruptedException, ExecutionException;
//在规定的时间如果没有返回结果就会抛出TimeoutException异常
V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;
}
---------------------
作者:tangedegushi
来源:CSDN
原文:https://blog.csdn.net/tangedegushi/article/details/80002297
版权声明:本文为博主原创文章,转载请附上博文链接!
// Callable 测试用例
public class MyThread3<T> implements Callable {
@Override
public T call() throws Exception {
System.out.println("local logic for Callable test.");
return null;
}
public static void main(String[] args) {
Callable<Integer> oneCallable = new MyThread3<Integer>();
FutureTask<Integer> oneTask = new FutureTask<>(oneCallable);
Thread thread = new Thread(oneTask);
thread.start();
boolean isDone = oneTask.isDone();
System.out.println("local logic for Callable test, isDone:" + isDone);
}
}
4、使用ExecutorService
用ExcecutorService实现线程创建(线程池),Excecutor以后开章节单独记。
// 线程池测试
public class MyThread4<Integer> implements Callable{
private Integer num;
public MyThread4(Integer num) {
this.num = num;
}
@Override
public Integer call() throws Exception {
return num;
}
public static void main(String[] args) {
int taskSize = 5;
ExecutorService pool = Executors.newFixedThreadPool(taskSize);
// 创建多个有返回值的任务
List<Future> list = new ArrayList<Future>();
for(int i = 0; i < taskSize; i++) {
Callable c = new MyThread4<>(i);
Future future = pool.submit(c);
list.add(future);
}
pool.shutdown();
// 获取所有并发任务的运行结果
for (Future future : list) {
try {
System.out.println("Thread : " + future.get().toString());
} catch (Exception e) {
}
}
}
}
参考: