简体   繁体   中英

Cannot assign value to static integer

I am working on a project with threads. This is the beginning of my main class.

public class Main {
    public static int firstIndex, secondIndex, thirdIndex, fourthIndex, fifthIndex;

Then I create a thread and override its run() function. Inside the run() I try to assign integers to my static integer variables that I defined earlier.

cThread thread1 = new cThread(ant) {
            @Override
            public void run() {
                try {
                    firstIndex = myAllocator.alloc(11, '1', this);
                    secondIndex = myAllocator.alloc(10, '2', this);

The alloc() function returns the correct integers inside, but the static variables always remain at 0 and do not change to the values that the function returns. However, if I do not make the integers static, it gives the following error:

Cannot make a static reference to the non-static field firstIndex.

I am sure the functions return correct values. What is the problem? Many thanks.

  1. If you are assigning values from a new thread, you should wait for the thread to complete before reading the values.

  2. Expecting writes to be seen by reads on different threads requires thread synchronization. Define the variables as volatile, or protect them with a lock.

Check the following things:

  • That you are running the thread. thread1.start()
  • That you are checking the static variables after the thread has completed. After all the purpose of threads is to run in parallel so you might be checking for the values before the thread has had a chance to run.
  • You need synchronization. Either make the static variables volatile or wrap your login inside the run method of the thread with a synchronized block. You will need to use a synchronized block when reading as well. It is possible that the values are being correctly set by one Core but a different Core is trying to read them. Without synchronization, you have no guarantee that both Cores will see the proper data. (due to caching and such)

Don't make the variables static; So you'd change your first line of code by

public int firstIndex, secondIndex,...

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