Reputation: 788
I have a problem in Java with threads. I am trying to pass an integer from the mainthread to another running thread in Java - but the value is always 0. Is there a way to solve this? I guess the reason why this happends is that threads have their own lives.
Here is the class that receives the integer - via an accessor-method. Then its supposed to be printed in the print-method - but as I mentioned, the value is ZERO.
class MyThread implements Runnable {
private int val;
public void run() {
printVal();
}
public void setValue(int val) {
this.val = val;
}
private void printVal() {
while (true) {
System.out.println("val: " + this.val);
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
}
}
}
}
Upvotes: 1
Views: 642