• Static方法在多线程环境下的运行


    最近看了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
    View Code

    看过结果之后,你会发现静态方法执行过程是随着线程的切换而交叉执行的【一会执行下Thread1 一会执行下Thread0】,但是每个线程的执行都有自己的执行环境【for 循环每一步都不会缺失(因为发生交叉覆盖导致循环混乱),最终sum结果都是45】,因此事隔离的。所以,随着的线程的切换,静态方法的参数环境也会发生变化(jvm计数器会记录当前线程上一次执行的位置(执行到哪个方法哪一行)),所以只要不是涉及共享变量,就不会出现并发问题。

  • 相关阅读:
    chrome浏览器,阻止回调方法中的window.open()方法
    安装1.4.2版本的Django
    noindex与nofllow标签的作用和用法
    mybatis中写sql语句时需要转义的字符
    GridView 导出到Excel
    (转)利用Cache防止同一帐号重复登录 (c#) .
    利用NPOI 导出文件到Excel (导出合同)
    TreeView控件的属性和事件【转】
    C# 数字货币转换大写方法
    Server 2003 IIS 发布网站
  • 原文地址:https://www.cnblogs.com/luyang08/p/6039277.html
Copyright © 2020-2023  润新知