美文网首页
多线程的三种常见实现方式

多线程的三种常见实现方式

作者: 我是白萝卜 | 来源:发表于2019-03-19 19:55 被阅读0次

    多线程有三种常见的实现方式:

    1. 继承Thread类,重写run方法。

    2. 实现Runnable接口,重写run方法。

    3. 通过实现Callable接口和使用FutureTask包装器来实现线程

    /**

    * 通过自己的类直接继承(extend) Thread,并复重写run()方法,就可以通过Thread类的start()方法启动线程,并执行自己定义的run()方法。Thread类的start()方法是启动线程的唯一方法。

    * @author Lucky

    */

    public class myThread_1 extends Thread{

    public void run(){

    System.out.println("方法1:继承Thread类,重写run方法");

    }

    public static void main(String args[]){

    myThread_1 m1=new myThread_1();

    myThread_1 m2=new myThread_1();

    m1.start();

    m2.start();

    }


    /**

    * 通过实现Runnable接口,重写run方法,将接口的实现类的实例作为参数传入带参的Thread构造函数中,然后就可以通过调用Thread类的start()方法启动线程。

    * @author Lucky

    * */

    class myt2 implements Runnable{

    public void run(){

    System.out.println("方法2:通过实现Runnable接口,重写run方法");

    }

    }

    public class myThread_2{

    public static void main(String args[]){

    //为了启动MyThread_2,

    //创建一个Runnable子类的对象,然后把这个对象当作参数传入Thread实例中,

    //这样就可以调用start()方法启动线程了。

    //start()是Thread类中的方法。

    myt2 m=new myt2();

    Thread t1= new Thread(m);

    t1.start();

    }

    }


    /**通过Callable和FutureTask创建线程 。 创建Callable接口的实现类 ,并实现Call方法 ;

    * 由Callable<Object>创建一个FutureTask<Object>对象;

    * FutureTask<Object>是一个包装器,它通过接受Callable<Object>来创建;

    * 由FutureTask<Object>创建一个Thread对象;

    * 最后通过调用Thread类的start()方法启动线程。

    * @author Lucky

    */

    import java.util.concurrent.Callable;

    import java.util.concurrent.FutureTask;

    public class myThread_3 {

    public static void main(String args[]){

    Callable<Object> c=new myt3<Object>();

    FutureTask<Object> f=new FutureTask<Object>(c);

    Thread t=new Thread(f);

    t.start();

    }

    }

    //创建Callable接口的实现类,并重写call()方法

    @SuppressWarnings("hiding")

    class myt3<Object> implements Callable<Object>{

    //重写call()方法

    public Object call() throws Exception{

    System.out.println("方法3:通过实现Callable接口和使用FutureTask包装器来实现线程");

    return null;

    }

    }

    相关文章

      网友评论

          本文标题:多线程的三种常见实现方式

          本文链接:https://www.haomeiwen.com/subject/heanmqtx.html