最近看了Jfinal 一致对model的那个static final dao有些疑惑,全局一个实例安全吗?同时也出了一个疑惑,静态方法执行会有并发影响吗?看代码
StaticThread.java
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 < 2; i++) { new Thread(new StaticThread()).start(); } } }
StaticAction.java
public class StaticAction {
public static void print() { int sum = 0; for (int i = 0; i < 10; i++) { System.out.println(Thread.currentThread().getName()+ " step " + i + " is running."); sum += i; } System.out.println("sum is " + sum); } }
执行结果如下,可以猜猜:1.sum是多少?2.执行过程是什么样子的?
Thread-0 step 0 is running. Thread-1 step 0 is running. Thread-1 step 1 is running. Thread-1 step 2 is running. Thread-1 step 3 is running. Thread-0 step 1 is running. Thread-1 step 4 is running. Thread-0 step 2 is running. Thread-1 step 5 is running. Thread-0 step 3 is running. Thread-0 step 4 is running. Thread-0 step 5 is running. Thread-0 step 6 is running. Thread-0 step 7 is running. Thread-0 step 8 is running. Thread-0 step 9 is running. sum is 45 Thread-1 step 6 is running. Thread-1 step 7 is running. Thread-1 step 8 is running. Thread-1 step 9 is running. sum is 45
看过结果之后,你会发现静态方法执行过程是随着线程的切换而交叉执行的【一会执行下Thread1 一会执行下Thread0】,但是每个线程的执行都有自己的执行环境【for 循环每一步都不会缺失(因为发生交叉覆盖导致循环混乱),最终sum结果都是45】,因此事隔离的。所以,随着的线程的切换,静态方法的参数环境也会发生变化(jvm计数器会记录当前线程上一次执行的位置(执行到哪个方法哪一行)),所以只要不是涉及共享变量,就不会出现并发问题。