首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

java语言轨范

2012-12-21 
java语言规范?阅读了2.17 Execution,2.15 Arrays,The?class?File Formathttp://java.sun.com/docs/books/j

java语言规范

?

阅读了2.17 Execution,2.15 Arrays,The?class?File Format

http://java.sun.com/docs/books/jvms/second_edition/html/Concepts.doc.html#16491

阅读8.1 Terminology and Framework至8.7章节

主内存和工作内存,read(main)、load(thread)、assign(thread)、store(thread)、write(main)、lock and unlock(thread)

线程之间不直接交互,都是通过主内存来交互的。

double和long双字节操作是非原子的,thread从main read-load是按单字节进行的

volatile只是轻量级的同步,保证可见性。thread use 之前会先从main load一把,thread在assign之后会紧跟着store一把。对volatile的操作是非原子的,写操作不能依赖于当前值,比如自增操作。

Locking can guarantee both visibility and atomicity; volatile variables can only guarantee visibility.

阅读8.7-8.14,完成第8章

class SynchSynchSimple {
??? int a = 1, b = 2;
??? synchronized void to() {
??? a = 3;
??? b = 4;
??? }
??? synchronized void fro()?
??? System.out.println("a= " + a + ", b=" + b);
??? }
}
一个时刻只能有一个线程获得对象锁,也就是说to fro不可能同时进行。There is a lock associated with every object,synchronized 其实是在执行方法体之前获得对象锁(锁和条件变量notify之类是java同步的两个重要武器)

Locking is not just about mutual exclusion; it is also about memory visibility

object.wait and object.notify()

http://www.zeroup.org/javas-synchronized-object-wait-object-notify-notifyall-works.html

如何获得对象锁

? * <li>By executing a synchronized instance method of that object.
???? * <li>By executing the body of a synchronized} statement
???? *???? that synchronizes on the object.
???? * <li>For objects of type Class,} by executing a
???? *???? synchronized static method of that class.

使用场景:并发对象发生变化调用notify,不可操作并发对象时调用wait。总是要先获得对象锁才能调用objg.wait(),总是以循环的形式使用wait.

  1. synchronized?(object)?{ ??
  2. ????//条件不成立时,则等待???
  3. ????while(条件不成立){ ??
  4. ????????try?{ ??
  5. ????????????object.wait(); ??
  6. ????????}?catch?(InterruptedException?e)?{ ??
  7. ????????????e.printStackTrace(); ??
  8. ????????} ??
  9. ????} ??
  10. ????//需要同步的代码???
  11. ????object.notifyAll(); ??
  12. }??

http://suo.iteye.com/blog/1199694

?

热点排行