Java多线程五种实现方式
- 继承Thread类
- 实现Runnable接口
- 匿名内部类
- 实现Callable接口通过FutureTask包装器来创建Thread线程
- 通过线程池创建线程,使用线程池接口ExecutorService结合Callable、Future实现有返回结果的多线程。
前面三种【无返回值】原因:通过重写run方法,run方法的返回值是void,所以没有办法返回结果。在run方法处理异常时,不能抛出异常,只能用try{ }catch(){}中捕获异常。
后面两种【有返回值】原因:通过Callable接口,就要实现call方法,这个方法的返回值是Object,所以返回的结果可以放在Object对象中。
1. 继承Thread方法
Thread类本质上是实现了Runnable接口的一个实例。通过自己的类直接 extends Thread,并重写run()方法,就可以启动新线程并执行自己定义的run()方法。
// Thread测试用例
public class MyThread extends Thread{
//重写run方法
public void run() {
System.out.println("MyThread run()");
}
public static void main(String[] args) {
MyThread myThread = new MyThread ();
System.out.println("myThread.start()");
//启动线程的唯一方法就是通过Thread类的start()实例方法
myThread.start();
}
}
运行结果:
myThread.start()
MyThread run()
JDK1.7 Thread类的start()方法源码,start0()方法是一个native方法,它将启动一个新线程,并执行run()方法。
public synchronized void start()
{
boolean flag;
if(threadStatus != 0)
throw new IllegalThreadStateException();
group.add(this);
flag = false;
start0();
flag = true;
try
{
if(!flag)
group.threadStartFailed(this);
}
catch(Throwable throwable) { }
break MISSING_BLOCK_LABEL_70;
Exception exception;
exception;
try
{
if(!flag)
group.threadStartFailed(this);
}
catch(Throwable throwable1) { }
throw exception;
}
private native void start0();
2. 实现Runnable接口
如果自己的类已经extends另一个类,就无法直接extends Thread【Java只支持单继承,不支持多继承。一个类只能有一个父类,不可以有多个父类。】,此时,可以实现一个Runnable接口
public class ThreadDemo {
public static void main(String[] args){
//实现类的实例作为Thread的target作为参数传入带参的Thread构造函数
Thread thread = new Thread(new MyThread());
System.out.println("thread.start()");
//调用start()方法启动线程
thread.start();
}
}
class MyThread extends Object implements Runnable{
@Override
public void run() {
System.out.println("MyThread run()");
}
}
运行结果:
thread.start()
MyThread run()
3. 使用匿名内部类
public class ThreadDemo {
public static void main(String[] args){
System.out.println("thread.start()");
//通过创建匿名内部类Runnable作为参数对象创建一个线程
Thread thread = new Thread(new Runnable() {
public void run() {
System.out.println("MyThread run()");
}
});
//调用start()方法启动线程
thread.start();
}
}
运行结果:
thread.start()
MyThread run()
4. 实现Callable接口通过FutureTask包装器来创建Thread线程
1). 创建Callable接口的实现类 ,并重写Call()方法
2). 使用Callable创建一个FutureTask对象,该FutureTask对象封装了Callable对象的Call方法的返回值
3). 使用futureTask对象作为Thread对象的target创建并启动线
4) .调用FutureTask对象的get()方法来获取返回值. 注意:get方法是阻塞的,即:线程无返回结果,get方法会一直等待。
public class ThreadDemo {
public static void main(String[] args) throws InterruptedException, ExecutionException {
Callable<Object> callable = new MyCallable();
//使用Callable<Integer>创建一个FutureTask<Integer>对象
FutureTask<Object> futureTask= new FutureTask<Object>(callable);
//使用futureTask对象作为Thread对象的target创建并启动线程
Thread thread = new Thread(futureTask);
System.out.println("thread start!");
thread.start();
System.out.println(futureTask.get().toString());
System.out.println("thread end!");
}
}
/**创建Callable接口的实现类 ,并实现Call方法*/
class MyCallable implements Callable<Object>{
//重写call方法
@Override
public Object call() throws Exception {
System.out.println("Tickets call...执行开始!");
return "Tickets call...执行完成!";
}
}
运行结果:
thread start!
Tickets call...执行开始!
Tickets call...执行完成!
thread end!
5. 通过线程池创建线程,使用线程池接口ExecutorService结合Callable、Future实现有返回结果的多线程。
ExecutorService、Callable、Future三个接口实际上都是属于Executor框架。需要有返回值的任务必须实现Callable接口。执行Callable任务后,可以获取一个Future的对象,Future对象的get方法就可以获取到Callable任务返回的Object了。
注意:get方法是阻塞的,即:线程无返回结果,get方法会一直等待。
public class ThreadPool {
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println("通过ExecutorService线程池 创建有返回值的任务开始……");
//创建一个线程池
ExecutorService pool = Executors.newCachedThreadPool();
Callable callable = new MyCallable();
//执行任务并获取Future对象
Future f = pool.submit(callable);
System.out.println(f.get().toString());
// 关闭线程池
pool.shutdown();
System.out.println("通过ExecutorService线程池 创建有返回值的任务结束!");
}
}
class MyCallable implements Callable<Object> {
@Override
public Object call() throws Exception {
System.out.println(">>>MyCallable call()任务启动……");
return ">>>MyCallable call()任务结束!";
}
}
运行结果:
通过ExecutorService线程池 创建有返回值的任务开始……
>>>MyCallable call()任务启动……
>>>MyCallable call()任务结束!
通过ExecutorService线程池 创建有返回值的任务结束!
扩展…1【Executors类】
Executors类:提供了一系列工厂方法用于创建线程池,返回的线程池都实现了ExecutorService接口。
ExecutorService接口:提供了submit()方法,传递一个Callable或Runnable,返回Future。如果Executor后台线程池还没有完成Callable的计算,这调用返回Future对象的get()方法,会阻塞直到计算完成。
//创建一个可缓存的线程池,调用execute 将重用以前构造的线程(如果线程可用)。如果现有线程没有可用的,则创建一个新线程并添加到池中。终止并从缓存中移除那些已有 60 秒钟未被使用的线程。
public static ExecutorService newCachedThreadPool()
//创建固定数目线程的线程池。
public static ExecutorService newFixedThreadPool(int nThreads)
//创建一个单线程化的Executor。
public static ExecutorService newSingleThreadExecutor()
//创建一个支持 [定时及周期性] 的任务执行的线程池,多数情况下可用来替代Timer类。
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize)
扩展…2【实际的java开发中是继承Thread类好,还是实现Runnable接口好?】
因为java是单继承,所以使用实现实现Runnable接口好,原因实现了接口还可以继续继承,继承了类不能再继承。
……
帮助他人,快乐自己,最后,感谢您的阅读!
所以如有纰漏或者建议,还请读者朋友们在评论区不吝指出!
……
个人网站…知识是一种宝贵的资源和财富,益发掘,更益分享…