0

How ClassThread can access to variable var from instance of Class1 that created this ClassThread instance?

ClassThread

public class ClassThread implements Runnable {
    @Override
    public void run() {

    }
}

Class1

public class Class1 implements Runnable{

    public volatile String var;

    public Class1() {

    }

    @Override
    public void run() {
        for(int i = 0; i < 5; i++){
            ClassThread ct = new ClassThread();
            Thread t = new Thread(ct);
            t.start();
        }
    }

}

Main

public class Main{
    public static void main(String[] args) {
        for(int i = 0; i < 3; i++){
            Class1 cla = new Class1();
            Thread t = new Thread(cla);
            t.start();
        }
    }
}

1 Answer 1

1

Take it as an argument in the constructor:

public class ClassThread implements Runnable {
    private volatile String var;

    public ClassThread(String var) {
        this.var = var;
    }

    @Override
    public void run() {

    }
}

And in Class1, pass it in when you construct the ClassThread:

@Override
public void run() {
    for(int i = 0; i < 5; i++){
        ClassThread ct = new ClassThread(var);
        Thread t = new Thread(ct);
        t.start();
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

And then changes to passed volatile variable will be visible to another threads?
String is immutable, you can't change it. If it were a List, or an Array, then yes, you could change the contents in one thread and then other threads would see the changes. BUT there is potential for race conditions and lost updates, make sure you understand synchronization before changing a variable from multiple threads.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.