小编fmz*_*ang的帖子

如何在Java中正确使用volatile

我正在研究Java Thread,volatile当我分析从例8.3.1.4修改的以下代码时,关键字让我感到困惑

public class Volatile {
    public static void main(String[] args){
        MyRunnable1 myRunnable1 = new MyRunnable1();
        MyRunnable2 myRunnable2 = new MyRunnable2();
        Thread t1 = new Thread(myRunnable1);
        Thread t2 = new Thread(myRunnable2);

        t1.start();
        t2.start();
    }
}

class MyRunnable1 implements Runnable{
    public void run(){
        while(true){
            Test1.one();
        }
    }
}
class MyRunnable2 implements Runnable{
    public void run(){
        while(true){
            Test1.two();
        }
    }
}

class Test1{
    static volatile int i = 0;
    static volatile int j = 0;
    static void one(){ …
Run Code Online (Sandbox Code Playgroud)

java multithreading volatile

7
推荐指数
1
解决办法
163
查看次数

为什么HashMap.put比较哈希和测试相等?

HashMap用Java 分析源代码并得到有关该put方法的问题.

以下是putJDK1.6中的方法:

public V put(K key, V value) {
    if (key == null)
        return putForNullKey(value);
    int hash = hash(key.hashCode());
    int i = indexFor(hash, table.length);
    for (Entry<K,V> e = table[i]; e != null; e = e.next) {
        Object k;
        if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
            V oldValue = e.value;
            e.value = value;
            e.recordAccess(this);
            return oldValue;
        }
    }

    modCount++;
    addEntry(hash, key, value, i);
    return null;
}
Run Code Online (Sandbox Code Playgroud)

我对此感到困惑 if …

java hashmap

6
推荐指数
2
解决办法
504
查看次数

标签 统计

java ×2

hashmap ×1

multithreading ×1

volatile ×1