zoukankan      html  css  js  c++  java
  • 实现多线程

    使用多线程的三种方式

    1、实现Runnable接口

    2、实现Callable接口

    3、继承Thread类

    4、jdk1.5之后,使用Executor线程池

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

    1、实现Runnable接口

     实现run方法

    public class MyRunnable implements Runnable {
    
        @Override
        public void run() {
            System.out.println("runnable ....");
        }
        public static void main(String[] args) {
            MyRunnable myRunnable = new MyRunnable();
            Thread thread = new Thread(myRunnable);
            thread.start();
        }
    }

    2、实现Callable接口

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

    public class MyCallable implements Callable<Integer> {
    
        @Override
        public Integer call() throws Exception {
            System.out.println("callable .....");
            return 1;
        }
        public static void main(String[] args) {
            MyCallable myCallable = new MyCallable();
            FutureTask<Integer> ft = new FutureTask<Integer>(myCallable);
            Thread thread = new Thread(ft);
            thread.start();
        }
    }

    3、继承Thread类

    public class MyThread extends Thread {
    
        @Override
        public void run() {
            System.out.println("myThread is running .....");
        }
        public static void main(String[] args) {
            MyThread myThread = new MyThread();
            myThread.start();
        }
    }

    4、实现接口 vs 继承 Thread

    ····实现接口会更好一些

    ···1)java是单继承,继承Thread类别的类就不能再继承,但是可以多实现

    ···2)类可能只要求可执行即可,继承整个Thread类的开销会很大

    5、Executor

     Executor 管理多个异步任务的执行,而无需程序员显示地管理线程的生命周期

       主要有三种Executor

       1)CachedThreadPool:一个任务创建一个线程;

       2)FixedThreadPool:所有任务只能使用固定大小线程数量;

       3)SingleThreadExecutor:相当于大小为1的FixedThreadPool。 

  • 相关阅读:
    【LeetCode】731. 图像渲染
    【LeetCode】130. 被围绕的区域
    小白之HTTP协议熟悉篇
    Java和js常用表达式
    Mysql主主复制高可用解决方案
    解决vue报错:Module build failed (from ./node_modules/_eslint-loader@2.2.1@eslint-loader/index.js): TypeError: Cannot read property 'range' of null
    centos7使用yum安装jdk并配置jdkhome
    阿里nacos安装及使用指南
    js实现给html固定区域增加水印
    MySQL安装教程
  • 原文地址:https://www.cnblogs.com/cherish010/p/8575038.html
Copyright © 2011-2022 走看看