实现多线程的方法有哪几种?

1)实现Runnable接口,并实现该接口的run()方法。

  • 自定义类并实现Runnable接口,实现run()方法
  • 创建Thread对象,用实现Runnable接口的对象作为参数实例化该Thread对象。
  • 调用Thread的start()方法

class MyThread implement Runnable{

        public void run(){//重写run方法

                    System.out.println("Thread body");

        }

}

public class Test{

        public static void main(String[] args){

              MyThread thread = new MyThread();

              Thread t = new Thread(thread);

              t.start();//开启线程

        }

}

 

2)继承Thread类,重写run方法

  • 继承Thread,重写run()方法
  • 创建一个MyThread实例
  • 执行start()方法

class MyTread extends Thread{

      public void run(){

            System.out.println("Thread body");

      }

}

public class Test{

      public static void main(String[] args){

            MyThread thread = new MyThread();

            thread.start();

      }

}

3)实现Callable接口,重写call()方法

      Callable对象实际是属于Executor框架中的功能类,Callable接口与Runnable接口类似,但是提供了比Runnable更强大的功能,主要表现为以下三点:

  • Callable可以在任务结束后提供一个返回值,Runnable无法提供这个功能。
  • Callable中的call()方法可以抛出异常,而Runnable的run()方法不能抛出异常。
  • 运行Callable可以拿到一个Future对象,Future对象表示异步计算的结果。它提供了检查计算是否完成的方法。由于线程属于异步计算模型,所以无法从其他线程中得到方法的返回值,在这种情况下,就可以使用Futrue来监视目标线程调用call()方法的情况,当调用Futrue的get()方法以获取结果时,当前线程就会阻塞,直到call()方法结束返回结果。

import java.util.concurrent.*;

public class CallableAndFutrue {
    
    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("waiting thread to finsish");
            System.out.println(future.get());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

运行结果:waiting thread to finsish
               Hello World!

 

总结:在以上三种方式中,前两种方式线程执行完后都没有返回值,只有最后一种是带返回值的。当需要实现多线程时,一般推荐实现Runnable接口的方式,原因如下:首先,Thread类定义了多种方法可以被派生类使用或重写,但是只有run()方法是必须被重写的,在run方法中实现这个线程的主要功能。这当然是实现Runnable接口所需的同样的方法。而且。很多Java开发人员认为,一个类仅在它们需要被加强或修改时才会被继承。因此,如果没有必要重写Thread类中的其他方法,那么通过继承Thread的实现方式与实现Runnable接口的效果相同,在这种情况下最好通过实现Runnable接口的方式来创建线程。

猜你喜欢

转载自blog.csdn.net/qq_41776884/article/details/81193344