实现Java线程安全的几种方法


实现线程安全总结来说存在四种方法:
1.    使用ThreadLocal----主要用于数据的传递
2.   synchronized----JVm来实现的
3.    lock----cpu的硬件指令
4.    使用Atomic类型----使用CPU的指令来实现
5.    并发包中读写分离CopyOnWriteArrayList等...
6    ......
 
package J2se;
/***
 * 实现一个类的线程安全
 * 
 * @author zhaolingzhi
 * 
 */
public class ThreadSafeWithThreadLocal {
 
private  ThreadLocal<String> t = new ThreadLocal<String>();
public void setT(String t) {
this.t.set(t);
}
public String getT() {
return this.t.get();
}
 
// private String name;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
public static void main(String[] args) {
ThreadSafeWithThreadLocal twtl = new ThreadSafeWithThreadLocal();
Visetor v1 = new Visetor(twtl, "zhao");
Visetor v3 = new Visetor(twtl, "ling");
Visetor v2 = new Visetor(twtl, "zhi");
 
v1.start();
v2.start();
v3.start();
 
}
 
}
class Visetor extends Thread {
ThreadSafeWithThreadLocal t;
private String name;
public Visetor(ThreadSafeWithThreadLocal t, String name) {
this.t = t;
this.name = name;
}
public void run() {
t.setT(name);
String tName = name;//String 是final类型的线程安全的对象
 
try {//让线程休眠,以便产生不安全现象
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread[" + Thread.currentThread().getName() + "] name[" + t.getT() + "]"
+ " (should be[" + tName + "])");
}
}
 
Thread[Thread-2] name[zhi] (should be[zhi])
Thread[Thread-0] name[zhao] (should be[zhao])
Thread[Thread-1] name[ling] (should be[ling])
其他略
 
更多讨论请加群:275524053
posted @ 2012-11-20 00:49  爬上树的山羊  阅读(683)  评论(0编辑  收藏  举报