---
title: "java随记"
author: "jiangsha"
date: "2013-04-27T14:41:50Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2013-04-27T14:45:28Z"
id: 1855886
url: "https://jiangsha.iteye.com/blog/1855886"
---

ThreadLocal是为解决多线程程序的并发问题而提出的，可以称之为线程局部变量。与一般的变量的区别在于，生命周期是在线程范围内的。

 

static变量是的生命周期与类的使用周期相同，即只要类存在，那么static变量也就存在。

 

static的ThreadLocal变量是一个与线程相关的静态变量，即一个线程内，static变量是被各个实例共同引用的，但是不同线程内，static变量是隔开的。

 

static变量在父类子类共用（除非在子类中复写该静态变量）。

```
public class Parent {
	public static String ab = "dd";
}
```

 

```
public class Child extends Parent{

	public static void main( String[] args ){		
		Child.ab = "child";
		System.out.println(Child.ab);
		
		System.out.println(Parent.ab);
	}
}
```

 输出:

      child

      child

 

```
public class Child2 extends Parent{

       public static String ab = "c";

	public static void main( String[] args ){		
		Child.ab = "child";
		System.out.println(Child.ab);
		
		System.out.println(Parent.ab);
	}
}
```

 输出：

      child

      ab