创建线程两种方式:
1 继承Thread类
2 实现Runnable接口
3 可以在线程完成任务后获取执行结果实现Coallable和Future
继承Thread类,必须重写run方法,在run方法中定义需要执行的任务
class MyThread extends Thread{
private static int num = 0;
public MyThread(){
num++;
}
@Override
public void run() {
System.out.println("主动创建的第"+num+"个线程");
}
}
run方法只是定义需要执行的任务,如果调用run方法,相当于在主线程中执行run方法,跟普通的方法调用没有任务区别,应该调用start方法去启动线程
public class Test {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
实现Runnable接口:
实现Runnable接口必须重写其run方法,通过实现Runnable接口,我们定义了一个子任务,然后子任务交由Thread去执行。将Runnable作为Thread类的参数,然后通过Thread的start方法来创建一个新线程来执行该子任务。如果单独调用Runnable的run方法的话,是不会创建新线程的,跟普通的方法调用没有任何区别。
public class Test {
public static void main(String[] args) {
System.out.println("主线程ID:"+Thread.currentThread().getId());
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
}
}
class MyRunnable implements Runnable{
public MyRunnable() {
}
@Override
public void run() {
System.out.println("子线程ID:"+Thread.currentThread().getId());
}
}
实现Callable和Future:
可以通过他们在任务执行完毕之后得到任务的执行结果
Callable是一个接口,它里面只声明了一个方法,call()
public interface Callable<V> {
/**
* Computes a result, or throws an exception if unable to do so.
*
* @return computed result
* @throws Exception if unable to compute a result
*/
V call() throws Exception;
}
这是一个泛型接口,call()函数返回的类型就是传递进来的V类型
Callable用于产生结果,Future用于获取结果
Callable一版配合ExecutorService来使用,在ExecutorService接口中声明若干个submit方法重载版本
<T> Future<T> submit(Callable<T> task);
<T> Future<T> submit(Runnable task, T result);//很少用
Future<?> submit(Runnable task);
第一个submit方法里面的参数类型就是Callable.
Future就是对于具体的Runnable or Callable任务的执行结果进行,取消,查询是否完成,获取结果。必要时通过get方法获取执行结果,该方法会阻塞知道任务返回结果。
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;
}
cancel方法用来取消任务,如果取消任务成功则返回ture,取消任务失败返回false,参数mayinterruptRunning表示是否允许取消正在执行却没有执行完毕的任务,如果设置为ture,表示可以取消正在执行的任务,如果取消已经执行玩的任务,会返回false,如果任务正在执行,mayinterruptifRunning设置为true,则返回true,如果mayinterruptifRunning设置为false,则返回false。如果任务还没有执行,则无论mayInterruptIfRunning为true还是false,肯定返回true
isCancelled方法标识任务是否别取消成功,如果任务正常完成被取消成功,则返回true。
isDone 方法标识任是否已经完成,若任务完成,则返回true。
get方法用来获取执行结果,这个方法会产生阻塞,会一直等到任务执行完毕才返回
get(long timeout, TimeUnit unit)用来获取执行结果,如果在指定时间内,还没有获取结果,就直接返回null。
总结:
Future提供了三种功能:
1 判断任务是否完成
2 能中断任务
3 能够获取任务执行结果
因为future是一个接口,无法直接用来创建对象,因此有了futureTask
public interface RunnableFuture<V> extends Runnable, Future<V> {
void run();
}
public class FutureTask<V> implements RunnableFuture<V>
FaskTask有两个构造器:
public FutureTask(Callable<V> callable) {
}
public FutureTask(Runnable runnable, V result) {
}
使用Callable+Future获取执行结果:
要点:
1 任务继承Callable
2 线程池submit(task)
3 用Future 接线程池的结果
public class Test {
public static void main(String[] args) {
ExecutorService executor = Executors.newCachedThreadPool();
Task task = new Task();
Future<Integer> result = executor.submit(task);
executor.shutdown();
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
System.out.println("主线程在执行任务");
try {
System.out.println("task运行结果"+result.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println("所有任务执行完毕");
}
}
class Task implements Callable<Integer>{
@Override
public Integer call() throws Exception {
System.out.println("子线程在进行计算");
Thread.sleep(3000);
int sum = 0;
for(int i=0;i<100;i++)
sum += i;
return sum;
}
}
结果:
子线程在进行计算
主线程在执行任务
task运行结果4950
所有任务执行完毕
使用Callable+FutureTask获取执行结果:
要点:
1 task继承Callable
2 new Task(),
3 创建FutureTask对象,FutureTask futureTask = new FutureTask(task);
4 线程池 submit(task)
public class Test {
public static void main(String[] args) {
//第一种方式
ExecutorService executor = Executors.newCachedThreadPool();
Task task = new Task();
FutureTask<Integer> futureTask = new FutureTask<Integer>(task);
executor.submit(futureTask);
executor.shutdown();
//第二种方式,注意这种方式和第一种方式效果是类似的,只不过一个使用的是ExecutorService,一个使用的是Thread
/*Task task = new Task();
FutureTask<Integer> futureTask = new FutureTask<Integer>(task);
Thread thread = new Thread(futureTask);
thread.start();*/
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
System.out.println("主线程在执行任务");
try {
System.out.println("task运行结果"+futureTask.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println("所有任务执行完毕");
}
}
class Task implements Callable<Integer>{
@Override
public Integer call() throws Exception {
System.out.println("子线程在进行计算");
Thread.sleep(3000);
int sum = 0;
for(int i=0;i<100;i++)
sum += i;
return sum;
}
}