首页 > 编程知识 正文

java如何定义线程类,创建线程有几种不同的方式

时间:2023-05-04 07:43:02 阅读:159630 作者:763

一、继承Thread方法;

首先,继承Thread方法,改写Thread的run ()方法

publicclassmythreadextendsthread { @ overridepublicvoidrun ()/todo auto-generatedmethodstub//super.run ); doSomething (; } privatevoiddosomething ((/todo auto-generatedmethodstubsystem.out.println ) (我是线程中的方法); 在main ()方法中创建一个MyThread对象,并调用该对象的start ()方法。 start ) )方法通过系统底层的一系列操作创建与当前线程同时执行的相应线程。 如果直接调用run ) )方法,则在程序执行run ) )方法之前,不会执行main ) )方法之后的代码。 因此,它运行在单线程而不是多线程上。 public class new thread { publicstaticvoidmain (string [ ] args ) mythread=newmythread; myThread.start (; //打开一个线程的方法//以下方法可以与上面的线程同时运行doSomething (); } privatestaticvoiddosomething ((/todo auto-generatedmethodstub ) }

二、实现Runnable接口

使用Runnable接口类似于继承Thread类

publicclassrunnablethreadimplementsrunnable { @ overridepublicvoidrun ((/todo auto-generatedmethodstubdosomething ) ) ) privatevoiddosomething ((/todo auto-generatedmethodstubsystem.out.println ) (我是线程方法) ); }不同之处在于,实现Runnable接口的类没有start (因为没有方法,所以在Thread中构建方法以打开线程

public class new thread { publicstaticvoidmain (string [ ] args ) runnable runnable=newrunnablethread }; thread thread=new thread (runnable; thread.start (; //打开一个线程的方法//以下方法可以与上面的线程同时运行doSomething (); } privatestaticvoiddosomething ((/todo auto-generatedmethodstub ) }

三.实现可编程接口和Future创建线程

首先,创建Callable接口的实现类CallableThread,实现call ()方法,并具有返回值。 Callable接口是一个通用接口,通用类型是线程返回值的类型。 实现Callable接口的call ()方法。 方法的返回类型与泛型类型相同。

publicclasscallablethreadimplementscallablestring { @ overridepublicstringcall (throws exception (/todo auto-generated mall } privatevoiddosomething ((/todo auto-generatedmethodstubsystem.out.println ) (我是线程中的方法); }}Callable无法直接获取返回值。 必须使用FutureTaskV将其封装在外部,然后才能获取返回值

public class new thread { publicstaticvoidmain (string [ ] args ) callablestringcallable=newcallablethread }; futuretaskstringfuturetask=newfuturetaskstring (callable ); thread thread=new thread (future task; thread.start (; //打开一个线程的方法//以下方法可以与上面的线程同时运行doSomething (); try {futureTask.get (; //获取线程返回值}交叉执行(catch )//todo auto-generatedcatchblocke.print stack trace ); }感谢您阅读privatestaticvoiddosomething (/todo auto-generatedmethodstub )。 如果觉得文章对你有帮助的话,麻烦你动手称赞一下,鼓励一下。 非常感谢!

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