一.使用场景
1.一个任务非常耗时,可以拆分为多个子任务,利用多线程技术来加速;
2.异步调用时,通常不关注任务的执行结果时,可以用多线程触发任务执行。
二.使用方式
1.继承Thread类
public class Aiou extends Thread {
public void run(){
System.out.println("this is thread test");
}
public static void main(String[] args){
Aiou aiou=new Aiou();
aiou.run();
}
}
2.实现Runnable接口
public class Aiou implements Runnable {
public void run(){
System.out.println("this is thread test");
}
public static void main(String[] args){
Aiou aiou=new Aiou();
aiou.run();
}
}
3.实现Callable接口
1和2的方式可以看到,run方法都是没有返回值的,也就是获取不到线程返回值,而Callable接口中需要实现call方法,且有返回值。
public class Aiouimplements Callable {
@Override
public Integercall()throws Exception {
System.out.println("this is a thread");
Integer sum=1;
return sum;
}
public static void main(String []args)throws Exception {
Aiou aiou=new Aiou();
FutureTask future =new FutureTask(aiou);
new Thread(future).start();
Integer result=future.get();
System.out.println(result);
}
}