我的getter不会给出更新的变量

时间:2022-11-26 10:10:37

I am trying to pass a variable to another class but my getter won't send the updated value of my variable it sends the value I used to initialize it.

我试图将一个变量传递给另一个类,但我的getter不会发送我的变量的更新值,它会发送我用来初始化它的值。

Main class:

    OtherClass otherclass = new OtherClass(new Main());
    private boolean updateVar = true
    private int timer = 0;

    public void tick(){

        if(updateVar == true) timer++;
    }

    public int getTimer(){

        return timer;
    }

Other Class:

    Main main;
    private int holdTimer;

    public OtherClass(Main main){

       this.main = main;
       holdTimer = this.main.getTimer();

          System.out.println(holdTimer);
    }

Every time it comes out as 0, Can anyone help? My tick() is being called by my thread every second in case you were wondering.

每次出现0时,有人可以帮忙吗?我的线程每秒都会调用我的tick(),以防你想知道。

2 个解决方案

#1


2  

Because you are calling tick() in another thread, you have entered the dark world of concurrency and thread safety.

因为你在另一个线程中调用tick(),所以你已经进入了并发和线程安全的黑暗世界。

Put simply, changes made in one thread are not necessarily visible to other threads, unless you follow some strict rules:

简而言之,除非您遵循一些严格的规则,否则在一个线程中所做的更改不一定对其他线程可见:

  • make the field volatile
  • 使该领域变得不稳定

  • all access to it must be synchronized
  • 必须同步对它的所有访问权限

Ergo:

private volatile int timer = 0;

public synchronized void tick(){
    if(updateVar == true) timer++;
}

pubic synchronized int getTimer(){
    return timer;
}

You may also have to join() the updating thread to wait for it to complete if you are not in a wait loop in the main thread.

如果您不在主线程中的等待循环中,您可能还必须加入()更新线程以等待它完成。

#2


0  

You need to call tick() if you want the member variable incremented.

如果希望成员变量递增,则需要调用tick()。

#1


2  

Because you are calling tick() in another thread, you have entered the dark world of concurrency and thread safety.

因为你在另一个线程中调用tick(),所以你已经进入了并发和线程安全的黑暗世界。

Put simply, changes made in one thread are not necessarily visible to other threads, unless you follow some strict rules:

简而言之,除非您遵循一些严格的规则,否则在一个线程中所做的更改不一定对其他线程可见:

  • make the field volatile
  • 使该领域变得不稳定

  • all access to it must be synchronized
  • 必须同步对它的所有访问权限

Ergo:

private volatile int timer = 0;

public synchronized void tick(){
    if(updateVar == true) timer++;
}

pubic synchronized int getTimer(){
    return timer;
}

You may also have to join() the updating thread to wait for it to complete if you are not in a wait loop in the main thread.

如果您不在主线程中的等待循环中,您可能还必须加入()更新线程以等待它完成。

#2


0  

You need to call tick() if you want the member variable incremented.

如果希望成员变量递增,则需要调用tick()。