zoukankan      html  css  js  c++  java
  • Java实现多线程的方式

    1.继承Thread类

    public class Demo extends Thread {
      public void run() {
        try {
          System.out.println("thread");
        } catch(Exception e) {
          e.printStackTrace();
        }
      }
    }
    
    public static void main(String[] args) {
        new Demo().start();
    }

    2.实现Runnable接口

    public class Demo implements Runnable{
        public void run() {
            try {
          System.out.println("runnable");
          } catch(Exception e) {
          e.printStackTrace();
              }
        }
    }
    
    public static void main(String[] args) {
        new Thread(new Demo()).start();
    }        

    3.实现Callable接口

    与Runnable相比,Callable功能更强大,可以返回值,可以跑出异常,支持泛型的返回值。

    需要借助FutureTask类获取返回结果,Future接口可以对Runnable、Callable任务执行结果进行取消、查询是否完成、获取结果等。

    FutureTask是Future接口的唯一实现类,FutureTask同时实现了Funnable和Future接口,既可以作为Runnable被线程执行,又可以作为Future得到Callable的返回值。

    public class Demo implements Callable<String>{
        public String call() throws Exception {
            System.out.println("callable");
            return "success";
        }
    }
    
    public static void main(String[] args) throws Exception {
        Callable<String> demo=new Demo();
        FutureTask<Strign> task=new FutureTask<>(demo);
        new Thread(task).start();
        System.out.println("线程返回值:"+task.get());
    }           

    4.使用线程池

    提前创建好多个线程,放入线程池中,使用时直接获取,使用完放回池中。可以避免频繁创建销毁、实现重复利用。

    提高响应速度,降低资源消耗,便于线程管理。

    public static void main(String[] args) throws Exception {
        ExecutorService pool=Executors.newFixedThreadPool(5);
        List<Future> list=new ArrayList<>();
        for(int i=0;i<5;i++) {
            Callable<String> c=new Demo();
            Future f=pool.submit(c);
            list.add(f);
        }
        pool.shutdown();
        for(Future f:list) {
            System.out.println("线程返回值"+f.get());
        }
    }
  • 相关阅读:
    python引用.py文件
    推荐系统之矩阵分解 转载 特别好
    数据挖掘之一元线性回归 python代码
    system服务文件讲解 转载
    bin sbin /usr/bin /usr/sbin区别 转载
    linux设置部门(或者学生部门)的共享目录
    Error establishing a database connection wordpress网站出现这个问题centos7的
    tomcat的java项目部署位置
    MAMP PRO教程
    MAMP使用简单教程
  • 原文地址:https://www.cnblogs.com/DreamFather/p/14574506.html
Copyright © 2011-2022 走看看