English 中文(简体)
学习使用线索,防止数据种族状况
原标题:Learning to use threads that prevent data race conditions

下面的法典应采用共同的同步方法,防止数据交换。 但出于某种原因,产出总是19915-19980。 如果数据没有数据记录,那么2000年数据是否应当?

public class SyncVarDataRace extends Thread {

    private static int common = 0;

    public void run(){
        synchronized((Integer)common){
            int local = common;
            local+=1;
            common = local;
        }
    }


    public static void main(String[] args) throws InterruptedException {
        SyncVarDataRace[] allThreads = new SyncVarDataRace[20000];

        for(int i = 0; i < allThreads.length; i++){
            allThreads[i] = new SyncVarDataRace();
        }

        for(SyncVarDataRace d: allThreads){
            d.start();
        }

        for(SyncVarDataRace d: allThreads){
            d.join();
        }

        System.out.println(common);
    }
}
最佳回答

你们正试图在汽车箱子上同步,这种物体将永远是一个不同的物体。

synchronized((Integer)common){

整个要点是,在每一线上对同一物体进行同步。 即使您将<代码>common改为Integer<>/code>,只要您将其分配到另一个价值,它就是一个不同的物体。

你们需要锁定一个不变的物体。 我建议界定一个地方。 您可以就以下事项协调:

 private final static Object lock = new Object();
 private static int common = 0;
 ...

 synchronized (lock) {
     common++;
 }

在这种具体情况下,你可能考虑使用<代码>AtomicInteger。 这使你能够做像以下这样的事情,而无需同步。

 private static AtomicInteger common = new AtomicInteger(0);
 ...

 // no need to synchronize since that is handled by the class
 common.incrementAndGet();
问题回答

暂无回答




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签