Code to simulate race condition in Java thread

后端 未结 4 2096
日久生厌
日久生厌 2021-01-05 07:15

I am new to Java multithreading. I am learning the concept of race condition.

Based on the Oracle document

http://docs.oracle.com/javase/tutorial/essential/

4条回答
  •  无人及你
    2021-01-05 07:40

    You are operating on a different object in each thread, thus there is no race condition.So first you need to share the SynchronizedCounter (btw this is a confusing name). Add a counter member in each runnable.

    CounterIncThread(SynchronizedCounter counter)
    {
       this->counter = counter;
    }
    
    CounterDecThread(SynchronizedCounter counter)
    {
       this->counter = counter;
    }
    
    ...
    SynchronizedCounter counter = new SynchronizedCounter();
    Thread thread1 = new Thread(new CounterIncThread(counter));
    Thread thread2 = new Thread(new CounterDecThread(counter));
    Thread thread3 = new Thread(new CounterIncThread(counter));
    

    Also. You are doing only one operation in the runnable. This may not be enough to display the race condition. So loop over a great amount of time.

    for(int i = 0; i < 100000; i++) <-- 100000 is just on the top of my head
    {
        counter.increment(); 
    }
    

    The value will not be the sum of the operation if the race occured,in my case I expect it to be 100000 * 2.

    To be even more explicit, run several time. You will likely obtain different values

提交回复
热议问题