Java 多线程--ThreadLocal Timer ExecutorService
ThreadLocal
/**
* ThreadLocal:每个线程自身的存储本地、局部区域
* @author xzlf
*
*/
public class ThreadLocalTest01 {
// private static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>();
// 更改初始化值
/*private static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>() {
protected Integer initialValue() {
return 100;};
};*/
private static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>().withInitial(()->50);
public static void main(String[] args) {
// 获取
System.out.println(Thread.currentThread().getName() +"-->" + threadLocal.get());
// 设置
threadLocal.set(200);
System.out.println(Thread.currentThread().getName() +"-->" + threadLocal.get());
}
}
**
* ThreadLocal:每个线程自身的数据,更改不会影响其他线程
* @author xzlf
*
*/
public class TheadLocalTest02 {
private static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>().withInitial(()->1);
public static void main(String[] args) {
for(int i=0; i<5; i++) {
new Thread(new MyRun()).start();
}
}
public static class MyRun implements Runnable{
@Override
public void run() {
int left = threadLocal.get();
System.out.println(Thread.currentThread().getName() + "得到了-->" + left);
threadLocal.set(left - 1);
System.out.println(Thread.currentThread().getName() + "还剩下-->" + threadLocal.get());
}
}
}
/**
* ThreadLocal:分析上下文 环境 起点
* 1、构造器: 哪里调用 就属于哪里 找线程体
* 2、run方法:本线程自身的
* @author xzlf
*
*/
public class TheadLocalTest03 {
private static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>() {
protected Integer initialValue() {
return 100;
};
};
public static void main(String[] args) {
new Thread(new MyRun()).start();
new Thread(new MyRun()).start();
}
static class MyRun implements Runnable{
public MyRun() {
threadLocal.set(200);
System.out.println(Thread.currentThread().getName() + "-->" + threadLocal.get());
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "-->" + threadLocal.get());
}
}
}
运行:
/**
* InheritableThreadLocal:继承环境上下文的数据,拷贝一份给子线程
*
* @author xzlf
*
*/
public class TheadLocalTest04 {
private static ThreadLocal<Integer> threadLocal = new InheritableThreadLocal<Integer>();
public static void main(String[] args) {
threadLocal.set(2);
System.out.println(Thread.currentThread().getName()+"-->"+threadLocal.get());
new Thread(()-> {
System.out.println(Thread.currentThread().getName() + "-->" + threadLocal.get());
threadLocal.set(100);
System.out.println(Thread.currentThread().getName() + "-->" + threadLocal.get());
}).start();
}
}
运行:
ExcutorService
线程池
public class TestFutrueTask {
public static void main(String[] args) throws InterruptedException, ExecutionException {
// 创建任务
MyCall call = new MyCall();
// 交给任务管理器
FutureTask<String> task = new FutureTask<String>(call);
// 创建代理类并启动线程
new Thread(task).start();
System.out.println("获取结果-->" + task.get());
System.out.println("任务是否执行完成-->" + task.isDone());
}
}
线程池执行带返回值的callable时需要加入到集合中,避免get() 等待结果是阻塞
package com.xzlf.testThread;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
public class TestPool2 {
public static void main(String[] args) throws Exception, Exception {
// 创建一个线程池,线程池中只有一个线程对象
// ExecutorService pool = Executors.newSingleThreadExecutor();
// 创建一个线程池,线程池中数量固定
ExecutorService pool = Executors.newFixedThreadPool(10);
// 创建一个线程池,线程池中数量可以动态改变
// ExecutorService pool = Executors.newCachedThreadPool();
List<Future<Integer>> list = new ArrayList<Future<Integer>>();
/**使用线程池执行大量的Callable任务*/
for (int i = 0; i < 20; i++) {
Callable<Integer> command = new Callable<Integer>() {
@Override
public Integer call() throws Exception {
Thread.sleep(2000);
return (int) (Math.random()*10);
}
};
// 将任务交给线程池
FutureTask<Integer> task =(FutureTask<Integer>) pool.submit(command);
list.add(task);
// pool.execute(task);
// System.out.println(task.get());
}
System.out.println("ok?");
for (Future<Integer> f : list) {
System.out.println(f.get());
}
System.out.println("ok!");
pool.shutdown();
}
}
运行:
Timer
package com.xzlf.testThread;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class TestTimer {
public static void main(String[] args) throws InterruptedException {
// 创建Timer对象
Timer timer = new Timer();
// 创建任务对象
TimerTask task = new Clock();
// 调用schedule()方法执行任务
timer.schedule(task, new Date(System.currentTimeMillis() + 2000), 1000);
Thread.sleep(5000);
timer.cancel();
}
}
/**
* 任务
* @author xzlf
*
*/
class Clock extends TimerTask{
DateFormat df = new SimpleDateFormat("yyyy-MM-DD HH:mm:ss");
@Override
public void run() {
Date date = new Date();
String dateStr = df.format(date);
System.out.println(dateStr);
}
}
运行:
Java 多线程--ThreadLocal Timer ExecutorService的更多相关文章
- Java多线程——ThreadLocal类的原理和使用
Java多线程——ThreadLocal类的原理和使用 摘要:本文主要学习了ThreadLocal类的原理和使用. 概述 是什么 ThreadLocal可以用来维护一个变量,提供了一个ThreadLo ...
- [Java多线程]-ThreadLocal源码及原理的深入分析
ThreadLocal<T>类:以空间换时间提供一种多线程更快捷访问变量的方式.这种方式不存在竞争,所以也不存在并发的安全性问题. //-------------------------- ...
- Java多线程ThreadLocal介绍
在Java多线程环境下ThreadLocal就像一家银行,每个线程就是银行里面的一个客户,每个客户独有一个保险箱来存放金钱,客户之间的金钱不影响. private static ThreadLocal ...
- java多线程--定时器Timer的使用
定时的功能我们在手机上见得比较多,比如定时清理垃圾,闹钟,等等.定时功能在java中主要使用的就是Timer对象,他在内部使用的就是多线程的技术. Time类主要负责完成定时计划任务的功能,就是在指定 ...
- Java多线程——ThreadLocal类
一.概述 ThreadLocal是什么呢?其实ThreadLocal并非是一个线程的本地实现版本,它并不是一个Thread,而是threadlocalvariable(线程局部变量).也许把它命名 ...
- 深入理解Java多线程——ThreadLocal
目录 定义 API 场景分析 场景实验,观察Spring框架在多线程场景的执行情况 10000此请求,单线程 10000次请求,线程数加到100 对c的访问加锁 把c设为ThreadLocal 收集多 ...
- Java多线程系列七——ExecutorService
java.util.concurrent.ExecutorService接口提供了许多线程管理的方法 Method 说明 shutdown 拒绝接收新的任务,待已提交的任务执行后关闭,且宿主线程不阻塞 ...
- JAVA多线程---ThreadLocal<E>
p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 13.0px ".SF NS Text" } tips: 1 当前ThreadLocal ...
- java多线程-ThreadLocal
大纲: 用法 源码 一.用法 ThreadLocal是一个容器,顾名思义就是把一个变量存到线程本地. class Test { public static void main(String[] arg ...
随机推荐
- coding++:快速构建 kindeditor 富文本编辑器(一)
此案例 demo 为 SpringBoot 开发 1.官网下载相关资源包:http://kindeditor.net/down.php 2.编写页面(引入相关JS) <!DOCTYPE html ...
- 《Java多线程编程实战指南(核心篇)》阅读笔记
<Java多线程编程实战指南(核心篇)>阅读笔记 */--> <Java多线程编程实战指南(核心篇)>阅读笔记 Table of Contents 1. 线程概念 1.1 ...
- 在Centos7下搭建大数据环境,即Zookeeper+Hadoop+HBase
1. 所需软件下载链接(建议直接复制链接到迅雷下载更快): ①hadoop-2.7.6.tar.gz: wget http://mirrors.tuna.tsinghua.edu.cn/apache/ ...
- L - Subway(最短路spfa)
L - Subway(最短路spfa) You have just moved from a quiet Waterloo neighbourhood to a big, noisy city. In ...
- Q - Marriage Match IV (非重复最短路 + Spfa + 网络最大流Isap)
Q - Marriage Match IV Do not sincere non-interference. Like that show, now starvae also take part in ...
- WDK驱动开发点滴
老程序员做新方向,老树发新芽,作为菜鸟的我,写点心得,用以记录并与同行交流 1对一些概念的理解: KMDF与UMDF.两者的框架,及使用VS生成的初始代码基本相同,只有所包含的头文件不同,链接的系统库 ...
- 1030 Travel Plan (30分)(dijkstra 具有多种决定因素)
A traveler's map gives the distances between cities along the highways, together with the cost of ea ...
- 【docker linux】linux系统镜像转化为docker镜像
概述 使用docker安装linux的同学都知道,你在docker提供的仓库安装linux系统,你就会体验到最精简的.最纯净的linux系统,当然,他会精简到你连ifconfig命令都需要自己配置,恰 ...
- 配置一个mariadb数据库《二》
mariadb 配置一个数据库 案例4:配置一个数据库 4.1 问题 本例要求在虚拟机 ...
- STM32CubeMX工程定时器配置
STM32CubeMX生成工程 选择自己的芯片型号 配置RCC寄存器时钟为外部晶振 单击芯片配置GPIO,选择输出方式,重命名标签等 进入时钟配置,本人使用的为8M外部晶振作为时钟源,PLL时钟源选择 ...