One thread increases an integer named "counter" , and another decreases the same integer.
Using synchronized statement on LockObject to control access to counter.
If i understand correctly i have to use an Object reference.
Can i use synchronized statement on counter somehow?
public class Synchronized_Block_Demo {
public static int counter=1;
public static Object LockObject = new Object();
public static void Show_LockObject(){
System.out.println("LockObject = " + counter);
}
public static void main(String[] args) throws InterruptedException {
Runnable r0=null,r1=null;
Thread a,b;
r0=new Thread_increases_LockObject();
r1=new Thread_decreases_LockObject();
a=new Thread(r0);
b=new Thread(r1);
a.start();
b.start();
a.join();
b.join();
System.out.print("Threads finished!");
}
}
class Thread_increases_LockObject implements Runnable{
public void run(){
try {
for(int i=0;i<10;i++){
Synchronized_Block_Demo.counter += 2;
Synchronized_Block_Demo.Show_LockObject();
synchronized (Synchronized_Block_Demo.LockObject) {
Synchronized_Block_Demo.LockObject.notify();
Synchronized_Block_Demo.LockObject.wait();
}
}
}
catch(InterruptedException e){}
}
}
class Thread_decreases_LockObject implements Runnable{
public void run(){
try {
for(int i=0;i<10;i++){
synchronized(Synchronized_Block_Demo.LockObject){
Synchronized_Block_Demo.LockObject.wait();
}
Synchronized_Block_Demo.counter -= 1;
Synchronized_Block_Demo.Show_LockObject();
synchronized (Synchronized_Block_Demo.LockObject) {
Synchronized_Block_Demo.LockObject.notify();
}
}
} catch(InterruptedException e){}
}
}