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());
        }
    }
  • 相关阅读:
    Principle of Computing (Python)学习笔记(5) BFS Searching + Zombie Apocalypse
    《Java从入门到精通》src9-25
    《Java从入门到精通》src0-8
    windows查看某个端口被谁占用
    css selector: xpath:
    awk 正则表达式
    Centos系统各种日志存详解
    mysql日志文件
    mysql主键设置成auto_increment时,进行并发性能測试出现主键反复Duplicate entry &#39;xxx&#39; for key &#39;PRIMARY&#39;
    递归函数时间复杂度分析
  • 原文地址:https://www.cnblogs.com/DreamFather/p/14574506.html
Copyright © 2011-2022 走看看