线程使用比较广泛,但实际上一般项目很少用上线程,线程常用于优化复杂的程序执行流程,把一些与业务关系关系不大但是必须要执行的流程使用线程的方式让子线程去执行,主流程只返回跟业务有关的信息

runnable是无返回值的执行线程;callable是有返回值的执行线程

实现runable接口的实现类通常使用execute来开启线程池中的线程来执行任务,但是也支持submit来开启原则上不会报错,因为实现类返回结果就是void

实现callable接口的实现类只能用submit来开启线程池中的线程来执行任务

下面是测试代码:

public class TestThread {

    private static int nThreads = Runtime.getRuntime().availableProcessors() * 2 + 1;

    private static ExecutorService executors = Executors.newFixedThreadPool(nThreads, new ThreadFactory() {

        private final String threadNamePrefix = "si_query_task_";

        private final AtomicInteger count = new AtomicInteger(1);

        @Override
public Thread newThread(Runnable r) {
Thread t = new Thread(Thread.currentThread().getThreadGroup(), r, threadNamePrefix + count.getAndIncrement());
t.setDaemon(true);
return t;
}
}); public static void main(String[] args) { List<Future<String[]>> fList = new ArrayList<>(); for (int i = 0; i < 10; i++) {
final int nextInt = new Random().nextInt(100);
Future<String[]> f = executors.submit(new TestTaskcb(nextInt));
fList.add(f);
} for (Future<String[]> future : fList) {
try {
String[] result = future.get();
// System.out.println(result[0] + " , 结果 " + result[1]);
} catch (InterruptedException e) {
} catch (ExecutionException e) {
}
}
System.out.println("call线程结束"); for (int i = 0; i < 10; i++) {
final int nextInt = new Random().nextInt(100);
executors.execute(new TestTaskvoid(nextInt));
}
System.out.println("void线程结束"); System.out.println("main 线程结束 "); } static class TestTaskcb implements Callable<String[]> { private int i; public TestTaskcb(int i) {
this.i = i;
} @Override
public String[] call() throws Exception {
String result = i % 2 == 0 ? "S" : "F";
// 业务处理逻辑
//Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + "第" + i + "次任务");
return new String[]{ Thread.currentThread().getName(), result };
}
} static class TestTaskvoid implements Runnable { private int i; public TestTaskvoid(int i) {
this.i = i;
} @Override
public void run() {
System.out.println(Thread.currentThread().getName() + "第" + i + "次任务");
}
}
}

线程执行是随机执行的,打印结果不可作参考

浅谈线程runnable和callable的使用及区别的更多相关文章

  1. 浅谈线程池(中):独立线程池的作用及IO线程池

    原文地址:http://blog.zhaojie.me/2009/07/thread-pool-2-dedicate-pool-and-io-pool.html 在上一篇文章中,我们简单讨论了线程池的 ...

  2. 浅谈线程池(上):线程池的作用及CLR线程池

    原文地址:http://blog.zhaojie.me/2009/07/thread-pool-1-the-goal-and-the-clr-thread-pool.html 线程池是一个重要的概念. ...

  3. Java线程—-Runnable和Callable的区别和联系

    Java 提供了三种创建线程的方法 1.继承Thread接口 public class Thread2Thread { public static void main(String[] args) { ...

  4. 浅谈JAVA GUI中,AWT与Swing的区别、联系及优缺点

    浅谈JAVA GUI中,AWT与Swing的区别.联系及优缺点 A.区别 1.发布的时间 AWT是在JDK 1.0版本时提出的 Swing是在AWT之后提出的(JAVA 2) 2. ”重量” AWT是 ...

  5. 浅谈头文件(.h)和源文件(.cpp)的区别

    浅谈头文件(.h)和源文件(.cpp)的区别 本人原来在大一写C的时候,都是所有代码写在一个文件里一锅乱煮.经过自己开始写程序之后,发现一个工程只有一定是由多个不同功能.分门别类展开的文件构成的.一锅 ...

  6. 浅谈Java语言中ArrayList和HashSet的区别

    Java语言中ArrayList和HashSet的区别 2019-04-10   13:22:49 一.基本区别 首先一起看个实例,其代码如下: package com.MrZ_baby.com; i ...

  7. 浅谈一下缓存策略以及memcached 、redis区别

    缓存策略三要素:缓存命中率   缓存更新策略  最大缓存容量.衡量一个缓存方案的好坏标准是:缓存命中率.缓存命中率越高,缓存方法设计的越好. 三者之间的关系为:当缓存到达最大的缓存容量时,会触发缓存更 ...

  8. 浅谈href=#与href=javascript:void(0)的区别

    #"包含了一个位置信息 默认的锚点是#top 也就是网页的上端 而javascript:void(0)  仅仅表示一个死链接 这就是为什么有的时候页面很长浏览链接明明是#可是跳动到了页首 而 ...

  9. 浅谈JS中的typeof和instanceof的区别

    JS中的typeof和instanceof常用来判断一个变量是否为空,或者是什么类型. typeof typeof运算符返回一个用来表示表达式的数据类型的字符串. typeof一般返回以下几个字符串: ...

随机推荐

  1. (转) GAN应用情况调研

    本文转自: https://mp.weixin.qq.com/s?__biz=MzA5MDMwMTIyNQ==&mid=2649290778&idx=1&sn=9816b862 ...

  2. Docker5之Deploy your app

    Make sure you have published the friendlyhello image you created by pushing it to a registry. We’ll ...

  3. 【译】第44节---EF6-存储过程映射

    原文:http://www.entityframeworktutorial.net/entityframework6/code-first-insert-update-delete-stored-pr ...

  4. HDU 4557 Tree(可持久化字典树 + LCA)

    http://acm.hdu.edu.cn/showproblem.php?pid=4757 题意: 给出一棵树,每个结点有一个权值,现在有多个询问,每次询问包含x,y,z三个数,求出在x到y的路径上 ...

  5. React创建组件的三种方式及其区别

    内容转载于http://www.cnblogs.com/wonyun/p/5930333.html React推出后,出于不同的原因先后出现三种定义react组件的方式,殊途同归; 具体的三种方式: ...

  6. xxx did not match any file(s) known to git

    切换分支的时候,报了标题这么个错误,error: pathspec ''xxx did not match any file(s) known to git. 看见不能切换分支,我首先 git sta ...

  7. bzoj 4034: [HAOI2015]树上操作 树链剖分+线段树

    4034: [HAOI2015]树上操作 Time Limit: 10 Sec  Memory Limit: 256 MBSubmit: 4352  Solved: 1387[Submit][Stat ...

  8. Centos7 安装python3.7.2

    下载python3.7.2源码 wget https://www.python.org/ftp/python/3.7.2/Python-3.7.2.tgz 下载完后对压缩包解压缩 tar -xf Py ...

  9. STL_string.ZC

    1.转成 小写/大写 #include <algorithm>using namespace std; // 转成小写transform(_strAttrNameG.begin(), _s ...

  10. Maven命令行创建java或javaWeb项目

    Maven命令行创建java或javaWeb项目   1.命令行创建普通java项目 mvn archetype:generate -DgroupId=com.fxust -DartifactId=d ...