Take a look at a class named Counter:
class Counter {
private int value = 0;
public void increment() {
value++;
}
public int getValue() {
return value;
}
}
And another class that extends Thread:
class MyThread extends Thread {
private Counter counter;
public MyThread(Counter counter) {
this.counter = counter;
}
@Override
public void run() {
counter.increment();
counter.increment();
counter.increment();
}
}
Inside the main method, an instance of the Counter is created and incremented twice. After that, the counter is passed to the constructor of MyThread to create an instance. Then the created instance of MyThread is started and the main thread joins for it.
// inside the main method
Counter counter = new Counter();
counter.increment();
counter.increment();
MyThread thread = new MyThread(counter);
thread.start();
thread.join(); // waiting for the thread
int result = counter.getValue();
The result ...