i have an Assignment about Multithreading and i need some help.
I have a Ressource class which cannot be changed
public class Ressource {
public int val;
public void incr() {
val++;
}
public void decr() {
val--;
}
And i have my main Class
public class TwoThreads {
public static Ressource res = new Ressource();
public static void main(String[] args) {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
for(int i = 0; i < 100; i++){
res.incr();
}
System.out.println(res.val);
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
for(int i = 0; i < 100; i++){
res.decr();
}
System.out.println(res.val);
}
});
t1.start();
t2.start();
}
}
I tried to use synchronized inside my Override methods but it didn't work. I know that if i used
public synchronized void incr() {
val++;
}
it will work but i should not change anything in the Ressources Class. Any Ideas?