Srikanth
Srikanth

Reputation: 247

How to update a value of a variable in Thread class on some condition in the caller

Let us say I have two classes, A main class and a Thread class as follows:

public class A {
   public static void main(String []args){
         int count = 0;
         for(int i = 0; i < 10; i++){
               count+=10;
               //here on every addition, I want to update the variable countOfAdd of the thread class 

//and when countOfAdd value is in multiples of 5 I want to print a statement
         }
  }

class B extends Thread {
    int countOfAdd;
    @Override
    public void run(){
         //on value received
         count+=1;
    }
}

I don't know whether this is possible or not. If it is possible how to do it

Thanks in advance.

Upvotes: 0

Views: 488

Answers (2)

9000
9000

Reputation: 40884

The normal way to do that is a queue.

Create a queue and make references to it available to both threads.

The main thread should add() an element to the queue (e.g. the amount of increment).

The other thread should poll() the queue and use this information to update its internal state.

This way none of the intermediate updates are going to be lost between the threads.

The quick and dirty way is direct access and locking.

Both of your threads can keep a reference to a common piece of data, and a common lock object (which can just be a Object commonLock = new Object()).

Every time either thread needs to access the data member, they do it holing a lock, e.g.:

synchronized (commonLock) { commonCount +=1; }  // One thread.
synchronized (commonLock) { if (commonCount > 1) {...} }  // Another thread.

This is harder to reason about, but can be made serviceable if the number of accesses in each thread is made small, preferably just one.

Upvotes: 1

Sumit Singh
Sumit Singh

Reputation: 15886

I don't know why you are using Thread here but anyway.

1. Without Thread

public class A {
   public static void main(String []args){
         int count = 0;
         B objectB = new B();
         for(int i = 0; i < 10; i++){
               count+=10;
               //here on every addition, I want to update the variable countOfAdd 
//of the thread class and when countOfAdd value is in multiples of 5 
//I want to print a statement
              objectB.setCount(YourInput);// set your value
              if(objectB.getValue()%5==0){
                //do your task
              }

         }
  }

class B {
    int countOfAdd;
    public int getCount(){return countOfAdd;}

    public void setCount(int ){this.countOfAdd =countOfAdd;}
}

2. With Thread Use Pub-sub pattern Implementation of pub sub pattern in Java

Upvotes: 0

Related Questions