java中实现多线程的方法有哪几种
实现多线程的方法有三种:
- 实现Runnable接口,并实现接口的run()方法
- 继承Thread类,重写run方法
- 实现Callable接口,重写call()方法
实现Runnable接口,并实现接口的run()方法
(1)自定义类并实现Runnable接口,实现run()方法。
(2)创建Thread对象,用实现Runnable接口的对象作为参数实例化该Thread对象。
(3)调用Thread的start()方法
class MyThread implements Runnable
{
public void run(){
System.out.println("线程运行");
}
}
public class Test{
public static void main(String[] args){
MyThread thread=new MyThread();
Thread t=new Thread(thread);
t.start();//开启线程
}
}
继承Thread类,重写run方法
当执行start()方法后,并不是立即执行多线程代码,而是使得该线程变为可运行态,什么运行多线程代码由操作系统决定。
class MyThread extends Thread{
public void run(){
System.out.println("线程运行");
}
}
public class Test{
public static void main(String[] args){
MyThread thread=new MyThread();
thread.start();//开启线程
}
}
实现Callable接口,重写call()方法
Callable对象属于Executor框架中的功能类,Callable与Runnable接口类似,但是提供了比Runnable更强大的功能:
- Callable可以在任务结束后提供一个返回值,Runnable无法提供这个功能。
- Callable中的call()方法可以抛出异常,而Runnable的run()方法不能抛出异常。
- 运行Callable可以拿到一个Future对象,Future对象表示异步计算的结果。可以使用Future来监视目标线程调用call()方法的使用情况,当调用Future的get()方法以获取结果是,当前线程就会阻塞,直到call()方法结束返回结果为止。
import java.util.concurrent.*;
public class CallableAndFuture{
//创建线程
public static class CallableTest implements Callable<String>{
public String call() throws Exception{
return "Hello World";
}
}
public static void main(String[] args){
ExecutorService threadPool=Executors.newSingleThreadExecutor();
//启动线程
Future<String> future=threadPool.submit(new CallableTest());
try{
System.out.println("等待线程执行完成");
System.out.println(future.get());//等待线程结束,并获取返回结果
}
catch(Exception e){
e.printStackTrace();
}
}
}
输出结果为:
等待线程执行完成
Hello World!
以上三种方式中,前两种方式线程执行完之后没有返回值,第三种有。一般推荐实现Runnable接口的方式,原因如下:Thread类定义了多种方法可以被派生类使用或重写,但是只有run方法是必须被重写
的,在run方法中实现这个线程的主要功能。所以没有必要继承Thread,去修改其他方法。
作者:Joeyos
来源链接:https://blog.csdn.net/zhangquan2015/article/details/82808579
版权声明:
1、JavaClub(https://www.javaclub.cn)以学习交流为目的,由作者投稿、网友推荐和小编整理收藏优秀的IT技术及相关内容,包括但不限于文字、图片、音频、视频、软件、程序等,其均来自互联网,本站不享有版权,版权归原作者所有。
2、本站提供的内容仅用于个人学习、研究或欣赏,以及其他非商业性或非盈利性用途,但同时应遵守著作权法及其他相关法律的规定,不得侵犯相关权利人及本网站的合法权利。
3、本网站内容原作者如不愿意在本网站刊登内容,请及时通知本站(javaclubcn@163.com),我们将第一时间核实后及时予以删除。