ITeye博客

strictfp 与 volatile

crazyox · 2007-10-19 22:51 · 开发交流 · Markdown

转自:http://hi.baidu.com/liyunqi1984/blog/item/0128921373d98b015aaf53eb.html

1. strictfp
修饰类和方法,意思是FP-strict,精确浮点,符合IEEE-754规范的。当一个class或interface用strictfp声明,内部所有的float和double表达式都会成为strictfp的。Interface method不能被声明为strictfp的,class的可以。
Example:

代码

  1. strictfp interface FPTest {
  2. void methodA();
  3. }
  4. class FPClass implements FPTest {
  5. public void methodA() {
  6. }
  7. public void methodB() {
  8. }
  9. public strictfp void methodC() {
  10. }
  11. }
  12. class FPClassB {
  13. strictfp void methodA() {
  14. }
  15. }

 

 

2.volatile
volatile修饰变量。在每次被线程访问时,都强迫从共享内存中重读该成员变量的值。而且,当成员变量发生变化时,强迫线程将变化值回写到共享内存。这样在任何时刻,两个不同的线程总是看到某个成员变量的同一个值。
看看Java Language Specification中的例子。
条件:一个线程不停的调用方法one(),一个线程不停的调用方法two()。我测试过多次,这种情况好像一直没有出现。

 

代码

  1. class Test {
  2. static int i = 0, j = 0;
  3. static void one() { i++; j++; }
  4. static void two() {
  5. System.out.println("i=" + i + " j=" + j);
  6. }
  7. }

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

代码

  1. class Test {
  2. static int i = 0, j = 0;
  3. static synchronized void one() { i++; j++; }
  4. static synchronized void two() {
  5. System.out.println("i=" + i + " j=" + j);
  6. }
  7. }

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

代码

  1. class Test {
  2. static volatile int i = 0, j = 0;
  3. static void one() { i++; j++; }
  4. static void two() {
  5. System.out.println("i=" + i + " j=" + j);
  6. }
  7. }

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。