• 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;  

                

            }

        }

     

       }

  • 相关阅读:
    css之background与第15周css补充内容叠用
    ios wkwebview didReceiveAuthenticationChallenge crash解决
    ios 版本更新提示-硬更新/软更新
    ios_UITextField-修改占位文字和光标的颜色,大小
    ios_UITextField右侧小圆叉
    ios_中将UITextField输入框设置为密码形式
    系统UISearchController详解
    iOS开发实战之搜索控制器UISearchController使用
    在iOS中如何正确的实现行间距与行高
    iOS alertController自带的输入框
  • 原文地址:https://www.cnblogs.com/liuchuanwu/p/4572278.html
Copyright © 2020-2023  润新知