0

I want to make an object in a new thread, that will create another thread. In that last created threads I need a reference for variable from exact object that created this thread. So far I have this code:

Main

public static void main(String[] args) {
    for(int i = 0; i < 2; i++){
        ClassThread ct = new ClassThread();
        Thread t = new Thread(ct);
        t.start();
    }
}

ClassThread

public static volatile int liczba = 1;
private static int id = 0;

@Override
public void run() {
    for(int i = 0; i < 2; i++){
        Class1 cla = new Class1(liczba, id);
        Thread t = new Thread(cla);
        t.start();
        id++;
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Class1

private volatile int var;
private int id;

public Class1(int _var, int _id) {
    var = _var;
    id = _id;
}

@Override
public void run() {
    while(true){
        System.out.println("Thread: " + id + " : " + var);
        var++;
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
sKhan
  • 9,694
  • 16
  • 55
  • 53
  • Do you need the Class1 object to have access to its parent ClassThread object? Is it the liczba variable that you are attempting to reference? Your 'public static volatile' variable can always be accessed using ClassThread.liczba, though I suggest you instead use an AtomicInteger if you would like atomic read-modify-write to happen (var++). – Erik Nyström Feb 13 '16 at 12:48
  • Integer is only as example. I need to get volatile variable from parent object of Class1, but also I want to make two or more instances of ClassThread – Michał Piątkowski Feb 13 '16 at 12:52

1 Answers1

1

If you need to get an int reference from one thread to another, you either have to specify your own MutableInteger class, or use AtomicInteger. The atomic integer has the positive side-effects in that operations can be made atomic. For a more exhaustive answer, see This answer.

If the question is regarding non-primitive types, you can simply pass the needed reference to the constructor as you are already attempting to do. Any changes to the internal state of that object will be reflected to all holders of a reference. Some objects are immutable (String being the perhaps most well-known, but be aware that Integer, Long, etc. works the same way.), and can therefore not be used in this way.

Do note that if you pass a reference, any assignments done to your internal reference var = "hello"; will not affect anything outside your class. You will simply exchange your private reference for another one, leaving all other references to the old object as they are. This has to do with the fact that Java is always pass-by-value.

Community
  • 1
  • 1
Erik Nyström
  • 537
  • 4
  • 9