zoukankan      html  css  js  c++  java
  • JDK5.0新增线程创建的方式

    新增方式一:实现Callable接口。 --- JDK 5.0新增

    //1.创建一个实现Callable的实现类
    class NumThread implements Callable{
        //2.实现call方法,将此线程需要执行的操作声明在call()中
        @Override
        public Object call() throws Exception {
            int sum = 0;
            for (int i = 1; i <= 100; i++) {
                if(i % 2 == 0){
                    System.out.println(i);
                    sum += i;
                }
            }
            return sum;
        }
    }
    
    
    public class ThreadNew {
        public static void main(String[] args) {
            //3.创建Callable接口实现类的对象
            NumThread numThread = new NumThread();
            //4.将此Callable接口实现类的对象作为传递到FutureTask构造器中,创建FutureTask的对象
            FutureTask futureTask = new FutureTask(numThread);
            //5.将FutureTask的对象作为参数传递到Thread类的构造器中,创建Thread对象,并调用start()
            new Thread(futureTask).start();
    
            try {
                //6.获取Callable中call方法的返回值
                //get()返回值即为FutureTask构造器参数Callable实现类重写的call()的返回值。
                Object sum = futureTask.get();
                System.out.println("总和为:" + sum);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
    
    }
    

    说明:

    * 如何理解实现Callable接口的方式创建多线程比实现Runnable接口创建多线程方式强大?
    * 1. call()可以返回值的。
    * 2. call()可以抛出异常,被外面的操作捕获,获取异常的信息
    * 3. Callable是支持泛型的
    

    新增方式二:使用线程池

    class NumberThread implements Runnable{
    
        @Override
        public void run() {
            for(int i = 0;i <= 100;i++){
                if(i % 2 == 0){
                    System.out.println(Thread.currentThread().getName() + ": " + i);
                }
            }
        }
    }
    
    class NumberThread1 implements Runnable{
    
        @Override
        public void run() {
            for(int i = 0;i <= 100;i++){
                if(i % 2 != 0){
                    System.out.println(Thread.currentThread().getName() + ": " + i);
                }
            }
        }
    }
    
    public class ThreadPool {
    
        public static void main(String[] args) {
            //1. 提供指定线程数量的线程池
            ExecutorService service = Executors.newFixedThreadPool(10);
            ThreadPoolExecutor service1 = (ThreadPoolExecutor) service;
            //设置线程池的属性
    //        System.out.println(service.getClass());
    //        service1.setCorePoolSize(15);
    //        service1.setKeepAliveTime();
    
    
            //2.执行指定的线程的操作。需要提供实现Runnable接口或Callable接口实现类的对象
            service.execute(new NumberThread());//适合适用于Runnable
            service.execute(new NumberThread1());//适合适用于Runnable
    
    //        service.submit(Callable callable);//适合使用于Callable
            //3.关闭连接池
            service.shutdown();
        }
    
    }
    

    说明:

    * 好处:
    * 1.提高响应速度(减少了创建新线程的时间)
    * 2.降低资源消耗(重复利用线程池中线程,不需要每次都创建)
    * 3.便于线程管理
    *      corePoolSize:核心池的大小
    *      maximumPoolSize:最大线程数
    *      keepAliveTime:线程没任务时最多保持多长时间后会终止
    

    面试题

    Java中多线程的创建有几种方式?四种。
    	1. 继承Thread类的方式
    	2. 实现Runnable接口的方式
    	3. 实现Callable接口。
    	4. 使用线程池
    
  • 相关阅读:
    nginx-1.8.1的安装
    ElasticSearch 在3节点集群的启动
    The type java.lang.CharSequence cannot be resolved. It is indirectly referenced from required .class files
    sqoop导入导出对mysql再带数据库test能跑通用户自己建立的数据库则不行
    LeetCode 501. Find Mode in Binary Search Tree (找到二叉搜索树的众数)
    LeetCode 437. Path Sum III (路径之和之三)
    LeetCode 404. Sum of Left Leaves (左子叶之和)
    LeetCode 257. Binary Tree Paths (二叉树路径)
    LeetCode Questions List (LeetCode 问题列表)- Java Solutions
    LeetCode 561. Array Partition I (数组分隔之一)
  • 原文地址:https://www.cnblogs.com/Krisone/p/13138995.html
Copyright © 2011-2022 走看看