![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/0012f3c18a9d32a705df5340f56c1463.png)
继承Thread类
1.写一个类,继承Thread类,重写run方法,用start方法启动线程;
public class Demo {
public static class MyThread extends Thread {
@Override
public void run() {
System.out.println("MyThread");
}
}
public static void main(String[] args) {
Thread myThread = new MyThread();
myThread.start();
}
}
注意:调用了start()后,线程才算是启动了!调用start()后,虚拟机会为我们创建一个线程,等到分到时间片了再调用run()方法。
不可以多次调用start()方法,否则会抛出异常!
实现Runnable接口
2.写一个类,实现Runnable接口,实现run方法,用new Thread(Runnable target).start()启动;
public class Demo {
public static class MyThread implements Runnable {
@Override
public void run() {
System.out.println("MyThread");
}
}
public static void main(String[] args) {
My Thread t = new MyThread();
new Thread(t).start();
}
}
Thread与Runnable的比较:
- 区别:
1.Runnable是接口,需要实现implements;Thread是类,需要继承extends;
2.由于Java单继承,多实现的特性,所以Runnable更加灵活;
3.Runnable更体现出了封装的思想,更符合面向对象的思想;
4.Runnable更加降低了耦合性,而且更轻量级;
So,本质上这两个属于实现的关系,Thread实现了Runnable接口并且进行了扩展,也没有什么可比性。 - 共同缺陷:
执行完任务后都无法获得执行结果,无返回值。(Callable+Future出现)
实现Callable接口
3.写一个类,实现Callable接口,实现call方法,不同的是有返回值
@FunctionalInterface
public interface Callable<V> {
V call() throws Exception;
}
Callable一般是配合线程池工具ExecutorService来使用的,这里使用submit方法来让一个Callable接口执行。它会返回一个Future,后续的程序可以通过这个Future的get方法得到结果。
class Task implements Callable<Integer>{
@Override
public Integer call() throws Exception {
Thread.sleep(1000);
return 2;
}
public static void main(String args[]){
ExecutorService executor = Executors.newCachedThreadPool();
Task task = new Task();
Future<Integer> result = executor.submit(task);
// 注意调用get方法会阻塞当前线程,直到得到结果。
// 所以实际编码中建议使用可以设置超时时间的重载get方法。
System.out.println(result.get());
}
}
Runnable和Callable的比较:
- 区别:
1.Callable核心是call()方法,有返回值,Runnable是run()方法,没有返回值;
2.Callable可以抛出异常,Runnable不可以; - 共同点:
1.都是接口;
2.都需要调用Thread.start();
3.都可以应用于executors类(ThreadPoolExecutor或ScheduledThreadPoolExecutor,它们都实现了ExcutorService接口),而thread类只支持Runnable。
具体可以看看两个接口源代码:
public interface Runnable {
public abstract void run();
}
public interface Callable<V> {
V call() throws Exception;
}
Callable和Runnable一般情况下是配合ExecutorService来使用的,在ExecutorService接口中声明了若干个submit方法的重载方法:
<T> Future<T> submit(Callable<T> task);
<T> Future<T> submit(Runnable task, T result);
Future<?> submit(Runnable task);
第一个方法是提交一个实现Callable接口的任务,返回封装了异步计算结果的Future。
第三个方法是提交一个实现Runnable接口的任务,返回封装了异步计算结果的Future。
Future接口
功能:对于具体任务进行【尝试取消】、【查询是否完成】、【获取执行的结果的一个接口】,位于java.util.concurrent包下。
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;
}
- get():用来获取执行结果,这个方法会产生阻塞,会一直等到任务执行完毕才返回;因此经常会有get(long timeout, TimeUnit unit)用来获取执行结果,如果在指定时间内,还没获取到结果,就直接返回null。
- cancel():试图取消一个线程的执行,并不一定能取消成功。
Callable+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
所有任务执行完毕
FutureTask类
FutureTask是个实现类,实现的是RunnableFuture接口。RunnableFuture接口同时继承了Runnable接口和Future接口。
有什么用呢?实现Future的cancel,get,isDone等方法!
class Task implements Callable<Integer>{
@Override
public Integer call() throws Exception {
Thread.sleep(1000);
return 2;
}
public static void main(String args[]){
ExecutorService executor = Executors.newCachedThreadPool();
FutureTask<Integer> futureTask = new FutureTask<>(new Task());
executor.submit(futureTask);
System.out.println(futureTask.get());
}
}
Callable+FutureTask获取执行结果
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;
}
}