zoukankan      html  css  js  c++  java
  • Java 实现多线程的三种方式

    转载自

    https://www.jianshu.com/p/19f9ce1d82a4

    继承 Thread 类

    run() 方法 VS start() 方法:

    • run() 方法:普通的成员方法
    • start() 方法:负责启动一个新的线程,并调用 run() 方法
    • 因此启动线程,需要使用 start() 方法
    public class MultiThread_Test {
        public static void main(String[] args) {
            MyThread mt = new MyThread();
            mt.start();
        }
    }
    
    class MyThread extends Thread {
        public void run() {
            System.out.println(Thread.currentThread().getName());
        }
    }
    

    实现 Runnable 接口

    实际上 Thread 类也是实现了 Runnable 接口:
    class Thread implements Runnable {}

    启动 Runnable 实例时,需要放在 Thread 中,然后调用 start() 方法

    public class MultiThread_Test {
        public static void main(String[] args) {
            MyRunnable mr = new MyRunnable();
            new Thread(mr).start();
        }
    }
    
    class MyRunnable implements Runnable {
        public void run() {
            System.out.println(Thread.currentThread().getName());
        }
    }
    

    实现 Callable 接口

    • Java 5 开始提供
    • 可以返回结果(通过 Future),也可以抛出异常
    • 需要实现的是 call() 方法
    • 以上两点也是 Callable 接口 与 Runnable 接口的区别
    public class MultiThread_Test {
        public static void main(String[] args) throws Exception {
            ExecutorService es = Executors.newSingleThreadExecutor();
    
            // 自动在一个新的线程上启动 MyCallable,执行 call 方法
            Future<Integer> f = es.submit(new MyCallable());
    
            // 当前 main 线程阻塞,直至 future 得到值
            System.out.println(f.get());
    
            es.shutdown();
        }
    }
    
    class MyCallable implements Callable<Integer> {
        public Integer call() {
            System.out.println(Thread.currentThread().getName());
    
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    
            return 123;
        }
    }
    
  • 相关阅读:
    dfs手写栈模板
    Remember the Word
    Sockets
    Sanatorium
    Exams
    Cormen — The Best Friend Of a Man
    win 7 普通家庭版 装IIS
    [引]构造文法时表达式中算符优先级的问题
    Chart系列(二):数据绑定
    算法整理篇之:数据结构 | 数组(1)
  • 原文地址:https://www.cnblogs.com/weixuqin/p/11429589.html
Copyright © 2011-2022 走看看