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);
}
}

运行:

最新文章

  1. Android 如何在Eclipse中查看Android API源码 及 support包源码
  2. android——彻底关闭——应用程序
  3. weblogic 双机集群搭建
  4. ubuntu更换阿里源
  5. Java开发笔记(八十四)文件与目录的管理
  6. centos7后台服务部署jar包
  7. 剑指offer 二叉树的层序遍历
  8. 小程序 showModal content换行
  9. 11g R2 RAC 虚拟机
  10. eclipse没有(添加)”Dynamic Web Project”选项的方法
  11. [React] 13 - Redux: react-redux
  12. jq demo--横向+展开菜单,支持m站
  13. 七、spring boot 1.5.4 集成shiro+cas,实现单点登录和权限控制
  14. Qt信号槽的一些事 Qt::带返回值的信号发射方式
  15. sencha touch list(列表) item(单行)单击事件触发顺序
  16. 分布式ID生成方法-趋势有序的全局唯一ID
  17. 安装ftp服务
  18. dvwa 源码分析(二) --- dvwaPage.inc.php分析
  19. shell-005:备份。
  20. windows程序 UAC设置,程序运行提示使用管理员权限运行的方法

热门文章

  1. python之路 2020/2/18
  2. link与@import区别整理,一个表格带你了解
  3. iOS 图片的解压缩
  4. JavaScript 异步、栈、事件循环、任务队列
  5. JDBC下Date类型转换问题
  6. python中装饰器的使用
  7. usdt钱包对接,usdt 对接交易平台,usdtapi,以太坊对接,以太坊代币对接
  8. Hadoop安装教程_伪分布式
  9. Pyspider的基本使用
  10. zendframework3