Java 的Runnable和Callable的区别

RunnableCallable的区别是,
(1)Callable规定的方法是call(),Runnable规定的方法是run().
(2)Callable
的任务执行后可返回值,而Runnable的任务是不能返回值得
(3)call方法可以抛出异常,run方法不可以
(4)运行Callable任务可以拿到一个Future对象,表示异步计算的结果。它提供了检查计算是否完成的方法,以等待计算的完成,并检索计算的结果。通过Future对象可以了解任务执行情况,可取消任务的执行,还可获取执行结果。

1.1使用Runnble接口 创建线程


public class RunnableTest implements Runnable {@Overridepublic void run() {System.out.println("this thread name is:"+Thread.currentThread().getName());}public static void main(String[] args) {System.out.println(Thread.currentThread().getName());RunnableTest r = new RunnableTest();Thread t = new Thread(r);t.start();}
}

或者使用匿名类实现:

Thread thread =new Thread(new Runnable() {public void run() {// TODO Auto-generated method stubSystem.out.println("匿名类实现线程");}

使用1.2 使用 Executors 创建线程

package com.asiainfo.proxydemo;import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;public class ThreadExecutorService {//设置线程的数量private  static int POOL_NUM=10;/*** @param args*/public static void main(String[] args) {
//		ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(3);
//		ExecutorService newFixedThreadPool = Executors.newCachedThreadPool();
//		ExecutorService newFixedThreadPool = Executors.newScheduledThreadPool(3);
//		ExecutorService newFixedThreadPool = Executors.newSingleThreadExecutor();ExecutorService newFixedThreadPool = Executors.newSingleThreadScheduledExecutor();for (int i = 0; i < POOL_NUM; i++) {RunnableImpl runnableImpl = new RunnableImpl("thread--"+i);newFixedThreadPool.execute(runnableImpl);}newFixedThreadPool.shutdown();}}
class RunnableImpl implements Runnable{private String name;public RunnableImpl(String name) {super();// TODO Auto-generated constructor stubthis.name=name;}public void run() {// TODO Auto-generated method stubSystem.out.println("hello ExecutorService"+name);}}

2.1 使用Callable 创建线程

package com.asiainfo.proxydemo;import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;public class ThreadCallable {/*** @param args*/
public static void main(String[] args) {Tickets<java.lang.Object> tickets = new Tickets<Object>();FutureTask<java.lang.Object> futureTask = new FutureTask<Object>(tickets);Thread thread = new Thread(futureTask);System.out.println(Thread.currentThread().getName());thread.start();
}
}
class Tickets<Object> implements Callable<Object>{/* (non-Javadoc)* @see java.util.concurrent.Callable#call()*/public Object call() throws Exception {// TODO Auto-generated method stubSystem.out.println(Thread.currentThread().getName()+"通过实现Callable接口通过FutureTask包装器来实现线程");return null;}}

     2.2 使用 Executors 结合Callable 创建多线程

      在Java5之 后,任务分两类:一类是实现了Runnable接口的类,一类是实现了Callable接口的类。两者都可以被ExecutorService执行,但是 Runnable任务没有返回值,而Callable任务有返回值。并且Callable的call()方法只能通过ExecutorService的 submit(Callable<T> task) 方法来执行,并且返回一个 <T> Future<T>,是表示任务等待完成的 Future.

  public interface Callable<V>返回结果并且可能抛出异常的任务。实现者定义了一个不带任何参数的叫做 call 的方法。

  Callable 接口类似于 Runnable,两者都是为那些其实例可能被另一个线程执行的类设计的。但是 Runnable 不会返回结果,并且无法抛出经过检查的异常。

  Executors 类包含一些从其他普通形式转换成 Callable 类的实用方法。

  Callable中的call()方法类似Runnable的run()方法,就是前者有返回值,后者没有。

  当将一个Callable的对象传递给ExecutorService的submit方法,则该call方法自动在一个线程上执行,并且会返回执行结果Future对象。

  同样,将Runnable的对象传递给ExecutorService的submit方法,则该run方法自动在一个线程上执行,并且会返回执行结果Future对象,但是在该Future对象上调用get方法,将返回null.

package com.asiainfo.proxydemo;import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;public class ThreadCallableDemo2 {public static void main(String[] args) {ExecutorService executorService = Executors.newCachedThreadPool();List<Future<String>> resultList = new ArrayList<Future<String>>();// 创建10个任务并执行for (int i = 0; i < 10; i++) {// 使用ExecutorService执行Callable类型的任务,并将结果保存在future变量中Future<String> future = executorService.submit(new TaskWithResult(i));// 将任务执行结果存储到List中resultList.add(future);}// 遍历任务的结果for (Future<String> fs : resultList) {try {System.out.println(fs.get()); // 打印各个线程(任务)执行的结果} catch (InterruptedException e) {e.printStackTrace();} catch (ExecutionException e) {e.printStackTrace();} finally {// 启动一次顺序关闭,执行以前提交的任务,但不接受新任务。如果已经关闭,则调用没有其他作用。executorService.shutdown();}}}
}class TaskWithResult implements Callable<String> {private int id;public TaskWithResult(int id) {this.id = id;}public String call() throws Exception {System.out.println("call()方法被自动调用,干活!!!             " + Thread.currentThread().getName());// 一个模拟耗时的操作for (int i = 999999; i > 0; i--);return "call()方法被自动调用,任务的结果是:" + id + "    " + Thread.currentThread().getName();}
}

参考:https://blog.csdn.net/w2393040183/article/details/52177572

http://murielily.blog.163.com/blog/static/134260649201131215237637/

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/423565.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Spring Boot----整合SpringCloud

首先比较一下Zookeeper和Eureka的区别&#xff1f; 1、CAP&#xff1a;C&#xff1a;强一致性&#xff0c;A&#xff1a;高可用性&#xff0c;P&#xff1a;分区容错性(分布式中必须有) CAP理论的核心是&#xff1a;一个分布式系统不可能同时很好的满足一致性&#xff0c;可用性…

[原创]利用Powerdesinger同步数据库的方法说明

本文主要介绍我在工作过程中如果利用PowerDesinger同步数据库设计PDM和物理数据库保持同步。PowerDesinger以下简称PD.我们经常在数据库生成后&#xff0c;在后续的开发中发现数据设计有遗漏&#xff0c;或者是少字段&#xff0c;或者是参照完整性不一致&#xff0c;那么我们都…

shiro学习(13):springMVC结合shiro完成认证

工具idea 先看看数据库 shiro_role_permission 数据 shiro_user shiro_user_role 数据 在pom.xml里面添加 <?xml version"1.0" encoding"UTF-8"?><project xmlns"http://maven.apache.org/POM/4.0.0" xmlns:xsi"http://www.w3…

分布式环境下,怎么保证线程安全

转:https://blog.csdn.net/Faker_Wang/article/details/80798732 避免并发 在分布式环境中&#xff0c;如果存在并发问题&#xff0c;那么很难通过技术去解决&#xff0c;或者解决的代价很大&#xff0c;所以我们首先要想想是不是可以通过某些策略和业务设计来避免并发。比如…

用小程序·云开发两天搭建mini论坛丨实战

笔者最近涉猎了小程序相关的知识&#xff0c;于是利用周末时间开发了一款类似于同事的小程序&#xff0c;深度体验了小程序云开发模式提供的云函数、数据库、存储三大能力。关于云开发&#xff0c;可参考文档&#xff1a;小程序云开发。 个人感觉云开发带来的最大好处是鉴权流程…

shiro学习(14):springMVC结合shiro完成认证

工具idea 先看看数据库 shiro_role_permission 数据 shiro_user shiro_user_role 数据 在pom.xml里面添加 <?xml version"1.0" encoding"UTF-8"?><project xmlns"http://maven.apache.org/POM/4.0.0" xmlns:xsi"http://www.w3…

mysql聚合函数rollup和cube

转:https://blog.csdn.net/liuxiao723846/article/details/48970443 一、with rollup&#xff1a; with rollup 通常和group by 语句一起使用&#xff0c;是根据维度在分组的结果集中进行聚合操作。——对group by的分组进行汇总。 假设用户需要对N个纬度进行聚合查询操作&am…

在C#里,如何执行cmd里的常用dos命令 (转)

http://blogger.org.cn/blog/more.asp?namenrzj&id4280 using System; using System.Diagnostics; namespace Tipo.Tools.Utility { /// <summary> /// 常用Dos命令操作 /// </summary> public class DosCommand { private Process processnull; pri…

Spring Boot----监控管理

用来监控spring 项目信息的 1、创建项目 1.1 启动项目 转载于:https://www.cnblogs.com/yanxiaoge/p/11400734.html

shiro学习(15):使用注解实现权限认证和后台管理

工具idea 先看看数据库 shiro_role_permission 数据 shiro_user shiro_user_role 数据 在pom.xml里面添加 <?xml version"1.0" encoding"UTF-8"?><project xmlns"http://maven.apache.org/POM/4.0.0" xmlns:xsi"http://www.w3…

什么是索引?索引类型有几种,各有什么特点?

转发: 索引是对数据库表中一列或多列的值进行排序的一种结构&#xff0c;例如 employee 表的姓&#xff08;name&#xff09;列。如果要按姓查找特定职员&#xff0c;与必须搜索表中的所有行相比&#xff0c;索引会帮助您更快地获得该信息。 索引是一个单独的、物理的数据库结…

设置Netbeans 6.5为英文界面

进入netbeans 6.5/etc目录&#xff0c;编辑netbeans.conf文件&#xff0c;将其中的#command line switchs下面那行添加启动参数&#xff1a; -J-Duser.languagezh -J-Duser.countryUS变为&#xff1a;netbeans_default_options"-J-client -J-Xss2m -J-Xms32m -J-XX:PermSi…

用小程序·云开发打造功能全面的博客小程序丨实战

用小程序云开发将博客小程序常用功能“一网打尽” 本文介绍mini博客小程序的详情页的功能按钮如何实现&#xff0c;具体包括评论、点赞、收藏和海报功能&#xff0c;这里记录下整个实现过程和实际编码中的一些坑。 评论、点赞、收藏功能 实现思路 实现文章的一些操作功能&#…

shiro学习(16):使用注解实现权限认证和后台管理二

工具idea 先看看数据库 shiro_role_permission 数据 shiro_user shiro_user_role 数据 目录结构 在pom.xml里面添加 <?xml version"1.0" encoding"UTF-8"?><project xmlns"http://maven.apache.org/POM/4.0.0" xmlns:xsi"http…

Javascript玩转Prototype(一)——先谈C#原型模式

在《Javascript玩转继承&#xff08;二&#xff09;》中&#xff0c;我使用了原型继承法来实现Javascript的继承&#xff0c;那原型究竟奥秘何在。在这篇文章中&#xff0c;我就主要针对原型来展开讨论。 抛开Javascript&#xff0c;我们先来看我们熟悉的常规的面向对象语言。…

hive的row_number()、rank()和dense_rank()的区别以及具体使用

参考:https://blog.csdn.net/qq_20641565/article/details/52841345?locationNum5&fps1 2016年10月17日 20:05:21 阅读数&#xff1a;4931 row_number()、rank()和dense_rank()这三个是hive内置的分析函数&#xff0c;下面我们来看看他们的区别和具体的使用案例。 首先…

HDU 1176 免费馅饼 (动态规划、另类数塔)

免费馅饼 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 76293 Accepted Submission(s): 26722 Problem Description 都说天上不会掉馅饼&#xff0c;但有一天gameboy正走在回家的小径上&#xff0c;忽然天上掉…

shiro学习(17):easyui布局测试

工具sublime <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><title>Document</title><link href"themes/black/easyui.css" rel"stylesheet" /><link href"themes…

细节差距

2008年过去的了&#xff0c;到现在还是没有空出时间来好好的来写下日志&#xff0c;不是自己没有时间而是自己知道可是由于自己的懒惰一直在推&#xff0c;导致的结果是所有需要做的时间一直在推。 人生路上也许很多时候你有很多的选择&#xff0c;在面临选择的时候怎么样作出选…

对比Oracle和Mysql在锁机制上的类似和差异点

转:https://blog.csdn.net/c332472988/article/details/52804078 InnoDB行锁实现方式 InnoDB行锁是通过给索引上的索引项加锁来实现的&#xff0c;这一点MySQL与Oracle不同&#xff0c;后者是通过在数据块中对相应数据行加锁来实现的。InnoDB这种行锁实现特点意味着&#xff1…