[英]synchronized method that use a public static HashTable from other class. How can I make this method thread safe?
suppose I have a synchronized method that use a public static HashTable from other class. 假设我有一个同步方法,该方法使用其他类的公共静态HashTable。 How can I make this method thread safe ?
如何使该方法线程安全? for my understanding any other thread can change this HashTable as it in other class and not in the class that holds the key (the class of the synchronized method) , doesn't it ?
就我的理解而言,任何其他线程都可以像其他类中那样更改此HashTable,而不是在拥有键的类(同步方法的类)中进行更改,不是吗?
Your understanding about the HashTable is not correct. 您对HashTable的理解不正确。 HashTable is Synchronized and thread safe.
HashTable是同步的并且是线程安全的。
Look into the source code of HashTable
. 查看
HashTable
的源代码。 All the public methods are synchronized. 所有公共方法都已同步。
public synchronized V put(K key, V value) {
public synchronized V get(Object key) {
public synchronized boolean contains(Object value) {
If you want to use your HashMap inside your synchronized method, it can work but only if all threads use the same instance of the class that contains both the method and the HashMap , for more clarity take a look at the example bellow : 如果要在同步方法中使用HashMap ,则它可以工作,但前提是所有线程都使用包含该方法和HashMap的类的相同实例,为更清楚起见,请看下面的示例:
Code Snippet 代码段
public class SynchronizedCounter {
private int c = 0;
public synchronized void increment() {
c++;
}
}
Now if all the threads use the same instance of SynchronizedCounter , we make sure only one thread is running the increment()
method at time, but if each thread is instantiating his own SynchronizedCounter instance then the method won't be thread safe. 现在,如果所有线程都使用同一个SynchronizedCounter实例,我们确保一次只有一个线程在运行
increment()
方法,但是如果每个线程都实例化自己的SynchronizedCounter实例,则该方法将不是线程安全的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.