public class Main {
private static final ThreadLocal threadlocal = new ThreadLocal<>();
public static void main(String[] args) {
threadlocal.set("父线程设置");
new Thread( () -> {
System.out.println("子线程读取" + threadlocal.get());
}).start();
System.out.println();
}
}
如果直接这样写的话是获取不到父线程的值的。
怎么解决呢
这里介绍俩种方式;
InheritableThreadLocal类
使用jdk自带的,InheritableThreadLocal
public class Main {
// 使用InheritableThreadLocal
private static final InheritableThreadLocal threadLocal = new InheritableThreadLocal<>();
public static void main(String[] args) {
threadLocal.set("父线程设置");
new Thread( () -> {
System.out.println("子线程读取\t" + threadLocal.get());
}).start();
System.out.println();
}
}
使用这个类实现threadlocal后可以发现可以读取到了;
那么是怎么实现的呢?
主要就是这俩个机制:线程创建时的值拷贝机制 和 Thread类的特殊设计
进入源码查看,
首先:InheritableThreadLocal集成了ThreadLocal类。
public class InheritableThreadLocal extends ThreadLocal {
public InheritableThreadLocal() {}
// 重写childValue方法(可自定义继承逻辑)
protected T childValue(T parentValue) {
return parentValue;
}
// // 关键方法:获取线程的inheritableThreadLocals变量
ThreadLocalMap getMap(Thread t) {
return t.inheritableThreadLocals;
}
void createMap(Thread t, T firstValue) {
t.inheritableThreadLocals = new ThreadLocalMap(this, firstValue);
}
}
这里写点抛砖引玉,希望大家能把自己整理的问题及解决方法晾出来,Mark一下,利人利己。
出现问题先搜一下文档上有没有,再看看度娘有没有,再看看论坛有没有。有报错要看日志。下面简单罗列下常见的问题,大多文档上都有提到的。
1、repeated column width is largerthan paper width:
这个看这段话应该是很好理解的。比如做的模板页面宽度只能放
这个问题我实在是为整个 springsource 的员工蒙羞
如果大家使用 spring 控制事务,使用 Open Session In View 模式,
com.mchange.v2.resourcepool.TimeoutException: A client timed out while waiting to acquire a resource from com.mchange.
简单模拟实现数据库连接池
实例1:
package com.bijian.thread;
public class DB {
//private static final int MAX_COUNT = 10;
private static final DB instance = new DB();
private int count = 0;
private i
using System;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace WindowsFormsApplication1
{
Configuring Spring and JTA without full Java EE
http://spring.io/blog/2011/08/15/configuring-spring-and-jta-without-full-java-ee/
Spring doc -Transaction Management
http://docs.spring.io/spri