|
Hi all,
I am new to this multithreading programming. I am working on an exercise where I was supposed to code two Thread objects accessing the same variable such that when one Thread changed the variable value will also change the variable value of another Thread. Is this possible?
Thanks
|
|
|
public class Synching {
int counter = 0;
int maxCount = 20;
public static void main(String[] args) {
Synching synching = new Synching();
new Worker(synching, "one").start();
new Worker(synching, "two").start();
}
synchronized void increment(Worker w) {
System.out.printf("%s incrementing count to %d%n",
w, ++counter);
}
boolean finished() {
return counter >= maxCount;
}
}
class Worker implements Runnable {
Synching synching;
String name;
Thread thread;
boolean working = false;
Worker(Synching s, String name) {
synching = s;
this.name = name;
}
public void run() {
while(working) {
if(synching.finished())
stop();
else
synching.increment(this);
}
}
void start() {
if(!working) {
working = true;
thread = new Thread(this);
thread.start();
}
}
void stop() {
working = false;
thread = null;
System.out.printf("%s stopped%n", this);
}
public String toString() {
return name;
}
}
|
|
|
|
|
|
|
|
|
|