开发者

what is synchronization of thread in java?

what is synchr开发者_运维问答onization of thread in java? give any example on it in detail


In multi-threaded programs there are often sections of the program that need to be run atomically (as if it were a single operation). These are generally referred to as critical regions and are protected using mutual exclusion (mutex) paradigms. The synchronized keyword in Java is one such way of providing mutual exclusion.

Consider the code:

synchronized(lockObject) {
  //critical code
}

In the above code, only one thread may enter that synchronized block at a time so long as the object reference by the variable lockObject is never changed. This ensures that the code executed within the synchronized block is only ever executed by a single thread.

Common examples of where locking is needed would be when iterating over a collection. Few Java Collection implementations offer thread safe iteration. A basic way of creating thread safe iteration would be to protect every access to the collection with a synchronized block on that collection.

For example:

synchronized(myCollection) {
  myCollection.add(item);
}

synchronized(myCollection) {
  myCollection.remove(item);
}

synchronized(myCollection) {
  for(Object item:myCollection){
     System.out.println(item);
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜