- java多线程实现方式
1.1 三种创建线程的方式
- 继承Thread类,重写run()方法
- 实现Runable()接口,重写run()方法
- 实现Callable()接口,重写call()方法
public class CreateMultiThread {
public static void main(String[] args) {
ThreadMethod1 threadMethod1 = new ThreadMethod1();
threadMethod1.start();
ThreadMethod2 threadMethod2 = new ThreadMethod2();
new Thread(threadMethod2).start();
ThreadMethod3 threadMethod3 = new ThreadMethod3();
FutureTask<Integer> futureTask = new FutureTask<>(threadMethod3);
Thread thread = new Thread(futureTask);
new Thread(thread).start();
try {
System.out.println(futureTask.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
class ThreadMethod1 extends Thread {
@Override
public void run() {
System.out.println("继承Thread类");
}
}
class ThreadMethod2 implements Runnable {
@Override
public void run() {
System.out.println("实现Runable接口");
}
}
class ThreadMethod3 implements Callable<Integer> {
@Override
public Integer call() throws Exception {
System.out.println("实现Callable接口");
return 1;
}
}
1.2 创建方式比较:
(1)java是单继承,使用方式1,将无法再继承其他类,建议用2,3
(2)实现Runable()接口,无法获取线程执行结果,如果需要返回值,使用方式3
1.3 Future,FutureTask
- Future类位于java.util.concurrent包下,它是一个接口,包含5个方法,主要用来对Runable或是Callable任务进行操作或是判断任务状态的
public interface Future<V> {
boolean cancel(boolean mayInterruptIfRunning);
boolean isCancelled();
boolean isDone();
V get() throws InterruptedException, ExecutionException;
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}
- FutureTask实现了RunnableFuture,而RunnableFuture继承了Runnable和Future,所以FutureTask可以作为Runnable被线程执行,也可以作为Future获取线程结果
public class FutureTask<V> implements RunnableFuture<V>
public interface RunnableFuture<V> extends Runnable, Future<V> {
void run();
}
- 线程池