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

     

    一种是继承Thread类,一种是实现Runable接口,还有一种是实现callable接口;

    有博主说只有前面2种方式,我个人愚见是三种,主要详细介绍下callable的使用;

    三种线程的我的个人理解:

    thread 是最简单的,简单粗暴也是最基础的,复写run()方法,start启动就好了;

    runable 是thread基础上的改进版本runable 主要的贡献在于实现了资源的共享,比如说在线选座的座位资源就需要共享这个时候就一定要使用runable,但是他也需要thread 的帮忙;

    callable 是主要用来处理异步,线程本身是消耗时间资源的所以,你有时候需要等他的处理结果,这个时候就需要callable;

    匿名threadable的创建使用方式;

     new Thread()

          {

             

             @Override

             public void run()

             {

                // TODO Auto-generated method stub

    // do something here            

             }

          }.start();

     

    匿名runable的创建使用方式

     new Thread(new Runnable()

          {

             

             @Override

             public void run()

             {

                // TODO Auto-generated method stub

                // do something here  

             }

          }).start();

     

     

     

     

    callable的创建使用方式

    public class CallableTest{

     

    /**

    测试案例是远程异步解密;

    */   

        public String decryption(String _ciphertext) {

            String result = "";

            // 创建一个线程池

            ExecutorService pool = Executors.newFixedThreadPool(2);

            Callable c = new CallableTest();

            // 执行任务并获取Future对象

            Future f = pool.submit(c);//配合使用拿数据的

            // 关闭线程池

            pool.shutdown();

            try {

                result = f.get().toString();

            } catch (InterruptedException e) {

                result = "";

            } catch (ExecutionException e) {

                result = "";

            }

            return result;

        }

     

        @SuppressWarnings("rawtypes")

        class CallableTest implements Callable {

          

               

     

           //区别于另两个线程的方式这里复写call()方法

            public String call() throws Exception {

                            

    // please dosomething   here;  

                

            }

        }

     

       }

  • 相关阅读:
    TTTTTTTTTTTTTTTTTTT UVA 2045 Richness of words
    hdu 5723 Abandoned country 最小生成树+子节点统计
    hdu 5792 World is Exploding 树状数组+离散化+容斥
    MySQL字符集详解
    MySQL的sql语言分类DML、DQL、DDL、DCL、
    MySQL5.6的4个自带库详解
    Win10下安装MySQL5.6
    {MySQL数据库初识}一 数据库概述 二 MySQL介绍 三 MySQL的下载安装、简单应用及目录介绍 四 root用户密码设置及忘记密码的解决方案 五 修改字符集编码 六 初识sql语句
    {python--GIL锁}一 介绍 二 GIL介绍 三 GIL与Lock 四 GIL与多线程 五 多线程性能测试
    Navicat安装及简单使用
  • 原文地址:https://www.cnblogs.com/liuchuanwu/p/4572278.html
Copyright © 2011-2022 走看看