简体   繁体   中英

Integer value not increment every time

I declare an int value that tries to increment every button click but some time value not increment and some after 2 or 3 click increment working. I always get log so click event no issue, already tried without static but still not working.

public static int TotalScore = 0;

btnsubmit.setOnClickListener(new View.OnClickListener() 
{
            @Override
            public void onClick(View view) {
                initScoreSubmit();
            }
 });

public void initScoreSubmit()
{

        TotalScore++;
        txtTotalPoint.setText("Total Point: " +   String.valueOf(TotalScore));

        settings.set(AppSettings.Key.UserTotalPoint, TotalScore);

        Log.d(TAG, "Total_point "+TotalScore);
}

Can you please tell me why not static value or only int not working.

Because of the Java memory model.

If one thread writes a variable and another reads the variable, the only ways to guarantee that the second thread sees the value written by the first are:

  • declare the variable as a volatile ,
  • synchronize the two threads, or
  • replace the bare variable with reference to a thread safe class; eg an AtomicInteger . The variable should be final .

You need to read the Oracle Tutorial on Concurrency, and specifically the sections on synchronization:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM