JDK 5.0 新增解决线程安全 Callable接口和线程池
在jdk5.0后又新增了两种解决线程安全的问题
一: 实现Callable接口,
实现接口步骤:
1: 创建一个实现Callable接口的实现类
2: 实现Callable接口中的call()方法, 讲此线程需要做的操作声明再这个方法中
3: 创建Callable 接口实现类的对象
4: 将创建对象传递到FutureTask构造器中,创建FutureTask对象
5: 将Future的对象作为参数传递到Thread类中 并调用thread的start()方法
6: 通过get()获取call方法中的返回值
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask; public class CallableTestTwo {
public static void main(String[] args) {
CallableT callableT = new CallableT(); // 3 : 实例化 实现Callable接口的类的对象
FutureTask futureTask = new FutureTask(callableT); // 4: 传递此对象到FutureTask 中 并实例化
new Thread(futureTask).start(); // 5: 生产对象传递到Thread 中并调用start()方法来启动线程 try { // 6: get获取call方法中抛出的信息 get方法必须搭配try来使用
Object val = futureTask.get();
System.out.println("总和是: "+val);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
} class CallableT implements Callable { // 1: 实现Calable接口
@Override
public Object call() throws Exception { // 2 :实现接口Callable接口中的call()方法
int num = 0;
for (int i = 0; i <= 100; i++) {
System.out.println(i);
num += i;
}
return num;
}
}
如何理解实现Callable接口的方式比创建多线程和实现Runnable接口的方式强大?
如何理解实现Callable接口的方式比创建多线程和实现Runnable接口的方式强大?
1: call方法可以有返回值
2: call方法可以抛出异常被外面的操作捕获, 获取异常信息
3: Callable是支持泛型的
二: 线程池
JDK 5.0起提供了线程池相关API:ExecutorService 和 Executors
ExecutorService:真正的线程池接口。常见子类ThreadPoolExecutor Executors:工具类、线程池的工厂类,用于创建并返回不同类型的线程池
ExecutorService 不能直接手动建立洗澡池子(线程)池子, 需要用工具一个铁湫之类的工具(Executors)来帮助建立线程.
Executors工具类的方法
Executors.newCachedThreadPool():创建一个可根据需要创建新线程的线程池
Executors.newFixedThreadPool(n); 创建一个可重用固定线程数的线程池
Executors.newSingleThreadExecutor() :创建一个只有一个线程的线程池
Executors.newScheduledThreadPool(n):创建一个线程池,它可安排在给定延迟后运 行命令或者定期地执行。
线程池创建的步骤:
1: ExecutorService 使用工具Executors创建线程池
2: 得到的对象使用对应线程的方法submit()或者execute() 操作对应线程
3: shutdown()停止线程
eg:
public class ExecutorsTest {
public static void main(String[] args) {
// 提供指定线程池的数量
// ExecutorService service = Executors.newFixedThreadPool(10);
//
//执行指定的线程的操作,需要提供实现Runnable或者Callable接口的实现的对象
service.submit(); // 适合使用于Callable
service.execute(); // 适合适用于Runnable
//关闭线程连接
// service.shutdown();
ExecutorService executorService = Executors.newFixedThreadPool(10);
executorService.execute(new RunnableT());
executorService.submit(new RunnableT());
executorService.shutdown();
}
}
import java.util.concurrent.*;
public class CallableTestThree {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(10);
RunnableTT runnableTT = new RunnableTT();
CallableTT callableTT = new CallableTT();
executorService.submit(callableTT); // submit可以对Callable 和Runnable接口的实现对象进行操作
executorService.submit(runnableTT);
//executorService.execute(callableTT); // execute()不可以获取 callable接口的实现对象 因为他只能对Runnable接口的实现对象进行操作
executorService.shutdown();
}
}
class RunnableTT implements Runnable{
@Override
public void run() {
System.out.println("这是取偶数");
for (int i = 0; i <= 100 ; i++) {
if(i % 2 == 0){
System.out.println(i);
}
}
}
}
class CallableTT implements Callable{
@Override
public Object call() throws Exception {
System.out.println("这是取奇数");
for (int i = 0; i <= 100 ; i++) {
System.out.println(i);
}
return null;
}
}
Executors工具的操作线程方法一般分为两种
submit(): 一般操作Callable
一般主要是操作Callable接口的线程对象, 偶尔可以用于Runnable接口实现的对象,推荐用Callable接口实现的对象
用来操作实现Callable 接口和Runnable接口的线程对象 , 两者都可以
execute(): 一般操作Runnable
只可以操作实现Runnable的接口线程对象
多线程可以理解为一个公交车 一个人就是线程, 你平时是自己走路快还是坐公交快和便捷呢?
肯定是坐公交,你不需要管线程池的问题 只需要管你自己就好了, 因为池子可以装多个线程公交可以装多个人
JDK 5.0 新增解决线程安全 Callable接口和线程池的更多相关文章
- 创建线程的方式三:实现Callable接口 --- JDK 5.0新增
/** * 创建线程的方式三:实现Callable接口. --- JDK 5.0新增 * * * 如何理解实现Callable接口的方式创建多线程比实现Runnable接口创建多线程方式强大? * 1 ...
- 实现Callable接口创建线程
创建执行线程有四种方式: 实现implements接口创建线程 继承Thread类创建线程 实现Callable接口,通过FutureTask包装器来创建线程 使用线程池创建线程 下面介绍通过实现Ca ...
- 通过Callable接口创建线程
通过Callable接口创建线程 一.前言 Java中创建线程的方式有四中,前两种在前面我已经详细介绍过了(Runnable和Thread),不清楚的朋友们可看这里: Java多线程之线程的启动以及J ...
- 创建线程的方式三:实现Callable接口。 --- JDK 5.0新增
如何理解实现Callable接口的方式创建多线程比实现Runnable接口创建多线程方式强大? call()可以有返回值的.call()可以抛出异常,被外面的操作捕获,获取异常的信息Callable是 ...
- 使用Callable接口创建线程和使用线程池的方式创建线程
1.使用Callable接口的方式实现多线程,这是JDK5.0新增的一种创建多线程的方法 package com.baozi.java2; import java.util.concurrent.Ca ...
- 多线程----Thread类,Runnable接口,线程池,Callable接口,线程安全
1概念 1.1进程 进程指正在运行的程序.确切的来说,当一个程序进入内存运行,即变成一个进程,进程是处于运行过程中的程序,并且具有一定独立功能. 任务管理器中: 1.2线程 线程是进程中的一个执行单元 ...
- Callable接口实现线程
public class CallableDemo { public static void main(String[] args) throws Exception, ExecutionExcept ...
- Java之创建线程的方式三:实现Callable接口
import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util ...
- 创建线程的方式三:实现Callable接口-----JDK5.0 新增
package com.yhqtv.java2; /* * 创建线程的方式三:实现Callable接口-----JDK5.0 新增 * * 如何理解实现Callable接口的方式创建多线程比实现Run ...
随机推荐
- 第五周总结&第三次实验报告
实验三 String类的应用 实验目的 掌握类String类的使用: 学会使用JDK帮助文档: 实验内容 1.已知字符串:"this is a test of java".按要求执 ...
- [Python3 填坑] 003 关键字?保留字?预留字?
目录 1. print( 坑的信息 ) 2. 开始填坑 2.1 问题的由来 2.2 网上搜索 2.3 结论 2.4 后记 1. print( 坑的信息 ) 挖坑时间:2019/01/04 明细 坑的编 ...
- hive Hbase sql
Hive和HBase的区别 hive是为了简化编写MapReduce程序而生的,使用MapReduce做过数据分析的人都知道,很多分析程序除业务逻辑不同外,程序流程基本一样.在这种情况下,就需要h ...
- 让网站动起来!12款优秀的 jQuery 动画
Textillate.js 介绍:Textillate.js 是一个简单的 CSS3 文本动画插件.结合了一些非常棒的库,把 CSS3 动画轻松应用到任何文本.只需要在项目中简单地引入 textill ...
- TVA金额的计算,以及应该放在那里
标记TTC价格的货物,有以下内容:TTC原价(自动提取),折扣(输入),折扣之后的减价(代金券,或者再次减价),最终TTC单价(自动计算).税率(输入),HT单价(自动计算),单价的税费(也可能不需要 ...
- 数组去重ES6
原文链接:https://juejin.im/post/5b17a2c251882513e9059231 1,去除简单类型 //ES6中新增了Set数据结构,类似于数组,但是 它的成员都是唯一的 ...
- SSM商城系统开发笔记-问题01-通配符的匹配很全面, 但无法找到元素 'mvc:annotation-driven' 的声明。
配置搭建完后进行Post请求测试时报错: Caused by: org.xml.sax.SAXParseException; lineNumber: 14; columnNumber: 29; cvc ...
- vue.js(14)--自定义全局指令
<input type="text" class="form-control" v-model="keywords" v-focus& ...
- sqoop使用中文手册
文章转载自:http://www.zihou.me/html/2014/01/28/9114.html 1. 概述 本文档主要对SQOOP的使用进行了说明,参考内容主要来自于Cloudera ...
- 2018-8-27-C#-powshell-调用
title author date CreateTime categories C# powshell 调用 lindexi 2018-8-27 16:20:4 +0800 2018-06-18 20 ...