zoukankan      html  css  js  c++  java
  • 关于线程的创建方式,线程池的作用

    线程的创建方式:

      1、线程继承Thread类,通过该对象的start()方法启动线程

      2、线程实现Runnable接口,通过往Thread类构造传入Runnable对象,thread.start()启动线程。

      3、线程实现Callable接口。Callable相当于run方法有返回值的Runnable,与Future结合使用(接收返回值使用Future)。

        

     使用过的例子:

    package thread;
    
    import java.util.concurrent.Callable;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.FutureTask;
    
    /**
     * @author zhen
     * @Date 2018/11/14 10:43
     */
    public class TestThread {
        public  static void main(String[] args) throws ExecutionException, InterruptedException {
    
            FutureTask<String> future = new FutureTask<>(new T3());
    
            new Thread(future).start();
            if (future.get() != ""){
                System.out.println(future.get());
            }
        }
    }
    class T1 extends Thread{
        @Override
        public void run() {
            System.out.println(1);
        }
    }
    class T2 implements Runnable{
        @Override
        public void run() {
    
        }
    }
    
    class T3 implements Callable<String>{
        @Override
        public String call() throws Exception {
            return "hello";
        }
    }

    线程池的使用,为什么使用线程池?

      复用线程,使用工作队列,避免无限制创建线程。重用线程降低开销,请求到达时,线程已存在,减少创建线程的等待时间,提高响应性。

  • 相关阅读:
    Shiro配置文件ini详解
    Shiro配置文件ini详解
    [转]shiro基础教程
    [转]shiro基础教程
    arguments.callee的作用
    [转] C# WPF Unable to add event handler
    [转] C# WPF Unable to add event handler
    springmvcajax json对象 用Map接受
    springmvcajax json对象 用Map接受
    json 对象字符串相互转化, js中
  • 原文地址:https://www.cnblogs.com/aigeileshei/p/9959223.html
Copyright © 2011-2022 走看看