首页 > 编程知识 正文

多线程的实现方式有哪三种,多进程和多线程的优缺点

时间:2023-05-03 23:45:07 阅读:14985 作者:3072

java有四种创建多线程的方法:1:继承Thread类创建线程

2:实现Runnable接口创建线程

3:使用Callable和FutureTask创建线程

4:使用线程池,例如用Executor框架创建线程

DEMO代码包线程; 导入Java.util.concurrent.*; public class threadtest { publicstaticvoidmain (字符串[ ] args ) throws ExecutionException,InterruptedException {//创建线程//创建线程的第二种方法Thread2 thread2=new Thread2(; threadthread=newthread(thread2; thread.start (; //创建线程的第三种方法callablestringcallable=new thread3(; futuretaskstringfuturetask=newfuturetask (callable ); thread thread3=new thread (future task ); thread3.start (; String s=futureTask.get (; 系统. out.println (s; //创建线程的第四种方法executor executor=executors.newfixedthreadpool (5); executor.execute(newrunnable () { @Override public void run ) } system.out.println (thread.current thread ) ) '线程); (ExecutorService ) executor (.shut down ); } class thread1extends thread { @ overridepublicvoidrun ((system.out.println ) thread.currentthread ) ) '创建线程的第一种方法class thread2implements runnable { @ overridepublicvoidrun (} { system.out.println )创建线程的第二个} class thread3implementscallablestring { @ overridepublicstringcall (throws exception ) returnthread.currentthread ) ' }线程

优点:线程类只是实现了Runnable接口或Callable接口,还可以继承其他类。 这种方式非常适合在多个相同线程上处理相同的资源,因为多个线程可以共享相同的target对象。 这样可以将CPU、代码和数据分开,形成清晰的模型,更好地表达面向对象的思想。 缺点:编程有点复杂,要访问当前线程,必须使用Thread.currentThread ()方法。 2、用继承Thread类的方法创建多线程

优点:如果创建简单且需要访问当前线程,则可以直接使用this检索当前线程,而无需使用Thread.currentThread ()方法。 缺点:线程类已经继承了Thread类,因此无法继承其他父类。 3、Runnable和Callable的区别

在Runnable接口中定义的run方法,在Callable中定义的是call方法。 run方法没有返回值。 call方法需要返回值。 run方法无法抛出异常。 call方法可以抛出checked exception。 Callable和Runnable都可以应用于执行程序。 另一方面,Thread类只支持Runnable。 总结在上述分析的基础上,建议通过实现Runnable接口、Callable接口的方式创建多线程。

如果大家对java架构相关感兴趣,可以关注下面公众号,会持续更新java基础面试题, netty, spring boot,spring cloud等系列文章,一系列干货随时送达, 超神之路从此展开, BTAJ不再是梦想!

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。