I have a public class change which holds the private static int commonresource and the methods :
public synchronized void increment(int inc)
public synchronized void decrement(int inc)
to handle the variable commonresource
I have a main class which starts 2 new threads "nikos" , "fosses"
with a constructor that takes as an argument an instance of class change.
change ch = new change();
(new Thread(new nikos(ch))).start();
(new Thread(new fosses(ch))).start();
nikos increments in a 10-times loop variable commonresource by 5 by calling ch.increment(5)
fosses decrements in a 10-times loop variable commonresource by calling ch.decrement(1);
package Threads;
public class change{
private static boolean flag = false;
private static int commonresource=1;
public synchronized void increment(int inc) {
while (flag){
try{
wait();
} catch (InterruptedException e) {}
}
flag = true;
{
System.out.println("before increment :"+commonresource);
commonresource += inc;
System.out.println(Thread.currentThread().getName()+" increment by "+inc);
System.out.println("after increment :"+commonresource);}
notify();
}
public synchronized void decrement(int inc) {
while (!flag){
try{
wait();
} catch (InterruptedException e) {}
}
flag = false;
{
System.out.println("before decrement :"+commonresource);
commonresource -= inc;
System.out.println(Thread.currentThread().getName()+" decrement by "+inc);
System.out.println("after decrement :"+commonresource);}
notify();
}
}
package Threads;
public class fosses implements Runnable {
private change ch;
public fosses(change ch) {
this.ch = ch;
}
@Override
public void run() {
for(int i =0; i<10;i++)
ch.decrement(1);
}
}
package Threads;
public class nikos implements Runnable {
private change ch;
public nikos(change ch) {
this.ch = ch;
}
@Override
public void run() {
for(int i =0; i<10;i++)
ch.increment(5);
}
}
package Threads;
public class fossesrunnable {
public static void main(String args[]) {
change ch = new change();
(new Thread(new nikos(ch))).start();
(new Thread(new fosses(ch))).start();
}}
This code seems to work fine but my question is :
Is there any other way to synchronize these two threads than trying to avoid a deadlock in class change body?