跨线程同步

ken*_*ken 1 java multithreading

以下代码应确保在所有线程之间同步对"sync"的访问.

根据输出结果并非总是如此,请注意Thread-3和Thread-4如何读取相同的sync值.

我在代码中遗漏了什么吗?

[Thread-0] before value of sync is 0
[Thread-0] after value of sync is 1
[Thread-3] before value of sync is 1
[Thread-3] after value of sync is 2
[Thread-4] before value of sync is 1
[Thread-4] after value of sync is 3
[Thread-2] before value of sync is 3
[Thread-2] after value of sync is 4
[Thread-1] before value of sync is 4
[Thread-1] after value of sync is 5
Run Code Online (Sandbox Code Playgroud)

这里的代码:

package com.mypackage.sync;

public class LocalSync implements Runnable {

    private Integer sync = 0;

    public void someMethod() {
        synchronized (sync) {
            System.out.println("[" + Thread.currentThread().getName() + "]" + " before value of sync is " + sync);
            sync++;
            System.out.println("[" + Thread.currentThread().getName() + "]" + " after value of sync is " + sync);
        }
    }

    @Override
    public void run() {
        someMethod();
    }

    public static void main(String[] args) {

        LocalSync localSync = new LocalSync();
        Thread[] threads = new Thread[5];
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(localSync, "Thread-" + i);
            threads[i].start();
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

JB *_*zet 6

您不断更改应同步所有线程的同步对象.因此,实际上,它们根本不同步.让你的同步变量最终,因为每个锁应该是,你会看到你的代码不再编译.

解决方案:同步另一个最终对象,或使用AtomicInteger并更改其值,或同步this(即使方法同步).