[size=medium]java线程安全分主要分2快[/size]
[b]1.实例变量且为单例模式为非线程安全,实例变量不为单例则线程安全
2.局部变量线程安全。[/b]
[b]实例变量线程模拟[/b]
[b]如果把上面红色的b改为new B() 即不是单例模式,则输出结果为:[/b]
[quote]
[当前线程]----------one=====实例变量的值----x=1
[当前线程]----------one=====实例变量的值----x=2
[当前线程]----------one=====实例变量的值----x=3
[当前线程]----------one=====实例变量的值----x=4
[当前线程]----------one=====实例变量的值----x=5
[当前线程]----------two=====实例变量的值----x=1
[当前线程]----------two=====实例变量的值----x=2
[当前线程]----------two=====实例变量的值----x=3
[当前线程]----------two=====实例变量的值----x=4
[当前线程]----------two=====实例变量的值----x=5
则最后x值为5
[/quote]
[b]局部变量线程模拟[/b]
[b]1.实例变量且为单例模式为非线程安全,实例变量不为单例则线程安全
2.局部变量线程安全。[/b]
[b]实例变量线程模拟[/b]
public class Test1 {
public static void main(String[] args) {
B b = new B();
Thread th1 = new Thread(b, "one"); //2个线程都对应同一个target对象b (单例模式)非线程安全
Thread th2 = new Thread([color=red]b[/color], "two");
th1.start();
th2.start();
}
}
class B implements Runnable{
public int x; // B类的实例变量
public void run() {
for(int i=0;i<5;i++){
x++;
System.out.println("[当前线程]----------"+Thread.currentThread().getName()+"====="+"实例变量的值----x="+x);
}
}
}
//==========================测试结果=================================
[当前线程]----------one=====实例变量的值----x=1
[当前线程]----------two=====实例变量的值----x=2
[当前线程]----------one=====实例变量的值----x=3
[当前线程]----------two=====实例变量的值----x=4
[当前线程]----------one=====实例变量的值----x=5
[当前线程]----------two=====实例变量的值----x=6
[当前线程]----------one=====实例变量的值----x=7
[当前线程]----------two=====实例变量的值----x=8
[当前线程]----------one=====实例变量的值----x=9
[当前线程]----------two=====实例变量的值----x=10
//由于2个线程维护同一个变量X 所以该x最后的值为10
[b]如果把上面红色的b改为new B() 即不是单例模式,则输出结果为:[/b]
[quote]
[当前线程]----------one=====实例变量的值----x=1
[当前线程]----------one=====实例变量的值----x=2
[当前线程]----------one=====实例变量的值----x=3
[当前线程]----------one=====实例变量的值----x=4
[当前线程]----------one=====实例变量的值----x=5
[当前线程]----------two=====实例变量的值----x=1
[当前线程]----------two=====实例变量的值----x=2
[当前线程]----------two=====实例变量的值----x=3
[当前线程]----------two=====实例变量的值----x=4
[当前线程]----------two=====实例变量的值----x=5
则最后x值为5
[/quote]
[b]局部变量线程模拟[/b]
package com.xxg.reflect;
public class Test1 {
public static void main(String[] args) {
B b = new B();
B b1 = new B();
Thread th1 = new Thread(b, "one"); //2个线程都对应同一个target对象b (单例模式)非线程安全
Thread th2 = new Thread(b, "two");
th1.start();
th2.start();
}
}
class B implements Runnable{
// B类的实例变量
public void run() {
[color=red]int x=0;[/color]
for(int i=0;i<5;i++){
x++;
System.out.println("[当前线程]----------"+Thread.currentThread().getName()+"====="+"实例变量的值----x="+x);
}
}
}
//===========================测试结果============================
[当前线程]----------one=====实例变量的值----x=1
[当前线程]----------one=====实例变量的值----x=2
[当前线程]----------one=====实例变量的值----x=3
[当前线程]----------one=====实例变量的值----x=4
[当前线程]----------one=====实例变量的值----x=5
[当前线程]----------two=====实例变量的值----x=1
[当前线程]----------two=====实例变量的值----x=2
[当前线程]----------two=====实例变量的值----x=3
[当前线程]----------two=====实例变量的值----x=4
[当前线程]----------two=====实例变量的值----x=5