发布网友 发布时间:2022-04-22 05:19
共1个回答
热心网友 时间:2023-07-16 01:34
总结论:java线程安全即任何(包括静态)都考虑线程冲突前提能存全局变量存全局变量则需要使用同步机制
通组比例讲解:
线程使用静态发事说线程访问同类static静态发事否发线程安全问题
public class Test {
public static void operation(){
// ... do something
}
}
事实证明要静态函数没处理线程共享数据存着线程访问同静态现资源冲突问题面看例:
public class StaticThread implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
StaticAction.print();
}
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
new Thread(new StaticThread()).start();
}
}
}
public class StaticAction {
public static int i = 0;
public static void print() {
int sum = 0;
for (int i = 0; i < 10; i++) {
System.out.print("step " + i + " is running.");
sum += i;
}
if (sum != 45) {
System.out.println("Thread error!");
System.exit(0);
}
System.out.println("sum is " + sum);