简体   繁体   English

什么是Java中的线程同步?

[英]what is synchronization of thread in java?

what is synchronization of thread in java? 什么是Java中的线程同步? give any example on it in detail 详细给出任何例子

看看有关同步的Java教程

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. Java中的synchronized关键字是提供互斥的一种方法。

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. 在上面的代码中,一次只能进入一个同步块,只要不更改变量lockObject引用的对象lockObject 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. 很少有Java Collection实现提供线程安全的迭代。 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);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM