java中线程安全是什意思_Java中关于线程安全是什么?

本文通过一个Java示例探讨了线程安全问题,包括变量安全和线程同步两方面,并提出了两种解决方案:使用多实例避免共享变量冲突及将变量封装在方法内部。

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

线程安全的本质体现在两个方面,

A变量安全:多线程同时运行一段代码

B线程同步:一个线程还没执行完,另一个线程又进来接着执行。

看个简单的例子。

Java代码

public class ThreadSafe implements java。

lang。Runnable {

int num = 1;

public void run() {

for (int i = 0; i < 3; i++) {

num = num + 1;

try {

Thread。sleep(2000);

} catch (InterruptedException e) {

e。

printStackTrace();

}

System。out。println("num is value +==="+Thread。currentThread()。getName()+"---------" + num);

}

}

}

TestMan。

java 写道

package com。java。thread。test;

public class TestMan {

public static void main(String[] args) {

Runnable safe=new ThreadSafe();

Thread thread1=new Thread(safe,"thread1");

Thread thread2=new Thread(safe,"thread2");

thread1。

start();

thread2。start();

}

}

运行结果

num is value +===thread2---------3

num is value +===thread1---------4

num is value +===thread2---------5

num is value +===thread1---------6

num is value +===thread1---------7

num is value +===thread2---------7

很明显是错误的,应为两个线程共享同一个变量。

这里就是变量的安全问题。

解决办法:

1抛弃单实例,多线程的方式,用多实例,多线程的方式,这样就和单线程是一个样了,不会出错,但是是最接近传统的编程模式

2不要用类的实例变量,经可能把变量封装到方法内部。

1类的解决办法的代码。

Java代码

public class TestMan {

public static void main(String[] args) {

Runnable safe=new ThreadSafe();

Runnable safe2=new ThreadSafe();

Thread thread1=new Thread(safe,"thread1");

Thread thread2=new Thread(safe2,"thread2");

thread1。

start();

thread2。

start();

}

}

运行结果

num is value +===thread1---------2

num is value +===thread2---------2

num is value +===thread1---------3

num is value +===thread2---------3

num is value +===thread1---------4

num is value +===thread2---------4。

全部

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值