实现多线程的三种方法

来源:互联网 发布:java中类的实例化 编辑:程序博客网 时间:2024/05/25 18:11
实现多线程的三种方法
Java虚拟机允许应用程序运行多个线程。在Java语言中多线程的实现一般有一下三种方法:
1、实现Runnable接口,并实现该接口的run()方法
以下是主要步骤:
1)、自定义类并实现Runnable接口,实现run()方法;
2)、创建Thread对象,用实现Runnable接口的对象作为参数实例化该Thread对象;
3)、调用Thread的start()方法。
class MyThread implements Runnable{    @Override    public void run() {        System.out.println("Thread start!");    }}public class Test {    public static void main(String[] args) {        MyThread thread = new MyThread();        Thread t = new Thread(thread);        t.start();        }}


2、继承Thread类,重写run()方法
Thread本质上也是实现Runnable接口的一个实例,它代表一个线程的实例,并且启动线程的唯一方法是通过Thread类的start()方法。start()方法是一个native(本地)方法,它将启动一个新线程,并执行run()方法(Thread方法中提供的run()方法是一个空方法)。这种方式通过自定义类直接extend(继承)Thread,并重写run()方法,就可以启动新线程并执行自己定义的run()方法。需要注意的是,当start()方法调用过后并不是立即执行多线程代码,而是是的该线程变为可运行状态(Runnable),什么时候运行多线程代码是由操作系统决定的。
class MyThread extends Thread{    @Override    public void run() {        System.out.println("Thread start!");    }}public class Test {    public static void main(String[] args) {        MyThread thread = new MyThread();        thread.start();        }}


3、实现Callable接口,重写call()方法
Callable对象实际是属于Executor框架中的功能类,Callable接口与Runnable接口类似,但是提供了比Runnable更强大的功能,主要表现为一下三点:
1)、Callable可以在任务结束后提供一个单回执,Runnable无法提供这个功能;
2)、Callable中的call()方法可以抛出异常,但是Runnable中的run()方法不能抛出异常;
3)、运行Callable可以拿到一个Future对象,Future对象表示异步计算的结果。它提供了检查计算是否完成的方法。由于线程属于异步计算模型,所以无法从其他相称中得到方法的返回值,在这种情况下,就可以使用Future来监视目标线程调用call()方法的情况,当调用Future的get()方法以获取结果时,当前线程就会阻塞,知道call()方法结束返回结果。
import java.util.concurrent.*;/** * Created by 胡柏青 on 2017/5/19. */public class CallableAndFuture {    //创建线程类    public static class CallableTest implements Callable<String>{        @Override        public String call() throws Exception {            return "Hello Word!";        }    }    public static void main(String[] args){        ExecutorService threadPool = Executors.newSingleThreadExecutor();        //启动线程        Future<String> future = threadPool.submit(new CallableTest());        try {            System.out.println("waiting thread to finish!");            System.out.println(future.get());        } catch (InterruptedException e) {            e.printStackTrace();        } catch (ExecutionException e) {            e.printStackTrace();        }    }}

在以上三种方式中,前两种方式线程执行完后没有返回值,只有最后一种是带有返回值的。
当需要实现多线程时一般推荐实现Runnable接口的方式,原因:首先,Thread类中定义了多种方法可以被派生类使用或重写,但是只有run方法是必须被重写的,在run方法中实现这个线程的只要功能。这也是实现Runnable接口所需的同样的方法。因此,如果没有必要重写Thread类中的其他方法,那么通过继承Thread的实现方法与实现Runnable接口的效果相同,这种情况下最好通过实现Runnable接口的方式创建线程。