java线程安全<一>

本文通过实例模拟解释了Java中实例变量和单例模式对线程安全的影响,展示了局部变量的线程安全性,并通过测试结果直观说明了不同变量作用域下线程执行的差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[size=medium]java线程安全分主要分2快[/size]

[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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值