• JAVA多线程实现的三种方式


    有三种使用线程的方法:

    • 实现 Runnable 接口;
    • 实现 Callable 接口;
    • 继承 Thread 类。

    实现 Runnable 和 Callable 接口的类只能当做一个可以在线程中运行的任务,不是真正意义上的线程,因此最后还需要通过 Thread 来调用。可以说任务是通过线程驱动从而执行的。

    实现 Runnable 接口

    需要实现 run() 方法。

    通过 Thread 调用 start() 方法来启动线程。

    public class MyRunnable implements Runnable {
        public void run() {
            // ...
        }
    }
    public static void main(String[] args) {
        MyRunnable instance = new MyRunnable();
        Thread thread = new Thread(instance);
        thread.start();
    }

    实现 Callable 接口

    与 Runnable 相比,Callable 可以有返回值,返回值通过 FutureTask 进行封装。

    public class MyCallable implements Callable<Integer> {
        public Integer call() {
            return 123;
        }
    }
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        MyCallable mc = new MyCallable();
        FutureTask<Integer> ft = new FutureTask<>(mc);
        Thread thread = new Thread(ft);
        thread.start();
        System.out.println(ft.get());
    }

    继承 Thread 类

    同样也是需要实现 run() 方法,因为 Thread 类也实现了 Runable 接口。

    当调用 start() 方法启动一个线程时,虚拟机会将该线程放入就绪队列中等待被调度,当一个线程被调度时会执行该线程的 run() 方法。

    public class MyThread extends Thread {
        public void run() {
            // ...
        }
    }
    public static void main(String[] args) {
        MyThread mt = new MyThread();
        mt.start();
    }

    实现接口 VS 继承 Thread

    实现接口会更好一些,因为:

    • Java 不支持多重继承,因此继承了 Thread 类就无法继承其它类,但是可以实现多个接口;
    • 类可能只要求可执行就行,继承整个 Thread 类开销过大。
  • 相关阅读:
    百奥谷
    3月13日火箭VS老鹰
    百度 hi 下载地址(内测版,正式版)
    中兴u980
    2008年清明节放假通知
    cyp740703 一个女人的自白
    黄唇鱼
    3月9日火箭vs黄蜂
    3月3日火箭vs掘金
    百度hi邀请码
  • 原文地址:https://www.cnblogs.com/AnXinliang/p/9868713.html
Copyright © 2020-2023  润新知