Search code examples
javamultithreadingsetterdecrement

Accessing a variable of a thread from another thread in java


I'm trying to access and modify a variable of a thread in another thread in java, and I really don't know how to do this.

ex :

Runnable r1 = new Runnable() {
    int value = 10;
    public void run() {
        // random stuff
    }
}
Runnable r2 = new Runnable() {
   public void run() {
        // of course the bellow line will not work
        r1.value--; // I want here to be able to decrement the variable "value" of r1
    }
}
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();

Is there any way to create a getter and setter for a thread in java?

Edit: the answers were good, but I was not clear in my question, I will try asking a better question


Solution

  • You could make it sort of work but, I suggest you use an AtomicInteger which is shared between threads.

    final AtomicInteger value = new AtomicInteger(10);
    Runnable r1 = new Runnable() {
        public void run() {
            // random stuff using value
        }
    }
    Runnable r2 = new Runnable() {
       public void run() {
            value.decrementAndGet();
        }
    }
    

    You can use AtomicReference for references to objects.