首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

Java中的native,transient,volatile跟strictfp关键字

2012-08-16 
Java中的native,transient,volatile和strictfp关键字?Java中的native,transient,volatile和strictfp关键字

Java中的native,transient,volatile和strictfp关键字

?

Java中的native,transient,volatile和strictfp关键字博客分类:?
  • J2SEJavaJ#JNIVC++Fortran#endif?
    /*?
    * Class: testdll?
    * Method: get?
    * Signature: ()I?
    */?
    JNIEXPORT jint JNICALL Java_testdll_get?
    (JNIEnv *, jclass);?

    /*?
    * Class: testdll?
    * Method: set?
    * Signature: (I)V?
    */?
    JNIEXPORT void JNICALL Java_testdll_set?
    (JNIEnv *, jclass, jint);?

    #ifdef __cplusplus?
    }?
    #endif?
    #endif?


    -------testdll.c-----------?
    #include "testdll.h"?

    int i = 0;?

    JNIEXPORT jint JNICALL Java_testdll_get (JNIEnv *, jclass)?
    {?
    return i;?
    }?

    JNIEXPORT void JNICALL Java_testdll_set (JNIEnv *, jclass, jint j)?
    {?
    i = j;?
    }}?
    }?

    结果偶尔会出现j大于i的情况,因为方法没有同步,所以会出现i和j可能不是一次更新。一种防止这种情况发生的办法就是声明两个方法为synchronized 的。?

    代码?
    class Test {?
    static int i = 0, j = 0;?
    static synchronized void one() { i++; j++; }?
    static synchronized void two() {?
    System.out.println("i=" + i + " j=" + j);?
    }?
    }?

    这样可以防止两个方法同时被执行,还可以保证j和i被同时更新,这样一来i和j的值一直是一样的。?
    另外一种途径就是把i和j声明为volatile。?

    代码?
    class Test {?
    static volatile int i = 0, j = 0;?
    static void one() { i++; j++; }?
    static void two() {?
    System.out.println("i=" + i + " j=" + j);?
    }?
    }?