zoukankan      html  css  js  c++  java
  • 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 类开销过大。
  • 相关阅读:
    [ Luogu 3398 ] 仓鼠找sugar
    [ JLOI 2014 ] 松鼠的新家
    AtcoderGrandContest 005 F. Many Easy Problems
    Codeforces 388 D. Fox and Perfect Sets
    Codeforces 1037 H. Security
    「学习笔记」wqs二分/dp凸优化
    「NOI2017」游戏
    「SCOI2014」方伯伯的商场之旅
    「SCOI2015」情报传递
    「SCOI2016」美味
  • 原文地址:https://www.cnblogs.com/AnXinliang/p/9868713.html
Copyright © 2011-2022 走看看