我正在开发一个带有线程的项目。这是我主要类(class)的开始。

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

然后,我创建一个线程并覆盖其run()函数。在run()内部,我尝试将整数分配给我之前定义的静态整数变量。
cThread thread1 = new cThread(ant) {
            @Override
            public void run() {
                try {
                    firstIndex = myAllocator.alloc(11, '1', this);
                    secondIndex = myAllocator.alloc(10, '2', this);

alloc()函数在内部返回正确的整数,但是静态变量始终保持为0,并且不会更改为该函数返回的值。但是,如果我不使整数成为静态,则会出现以下错误:
Cannot make a static reference to the non-static field firstIndex.

我确定函数会返回正确的值。问题是什么?非常感谢。

最佳答案

检查以下内容:

  • 您正在运行线程。 thread1.start()
  • 线程完成后,您正在检查静态变量。毕竟线程的目的是并行运行,因此您可能需要在线程有机会运行之前检查这些值。
  • 您需要同步。可以将静态变量设置为volatile,也可以使用run块将登录名包装在线程的synchronized方法中。阅读时,您还需要使用同步块(synchronized block)。一个内核可能已正确设置了这些值,但另一个内核正在尝试读取它们。如果没有同步,则无法保证两个Core都能看到正确的数据。 (由于缓存等原因)
  • 10-06 05:11
    查看更多