关于多线程出现安全问题的一个小示例

本文通过一个简单的并发编程案例,展示了在线程切换过程中可能导致的数据不一致问题。通过分析代码,我们发现当一个线程正在修改共享资源时,另一个线程读取了这个资源,导致输出结果的混乱。

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

class Sources
{
String name;
String sex;
}
class inPut implements Runnable
{
Sources s;
inPut(Sources s)
{
this.s=s;
}
public void run()
{
int x=0;
while(true)
{
if(x==0)
{
this.s.name="三公子";
this.s.sex="男";




}
else
{
this.s.name="三公主";
this.s.sex="女";




}
x++;
x=x%2;
}
}
}
class outPut implements Runnable
{
Sources s;
outPut(Sources s)
{
this.s=s;
}
public void run()
{
while(true)
{
System.out.println(Thread.currentThread().getName()+" "+s.name+"     "+s.sex);
}
}
}
class  Name
{
public static void main(String[] args) 
{
Sources s=new Sources();
inPut in=new inPut(s);
outPut out=new outPut(s);
Thread td1=new Thread(in);
Thread td2=new Thread(out);
td1.start();
td2.start();
System.out.println("Hello World!");
}
}



 分析:出现这种的情况的原因?

答:

this.s.name="三公子";
this.s.sex="男";
这句的时候突然切换到了其他线程执行 this.s.name="三公主";,所以当输出的时候就出现了这样的情况.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值