I have modified the Vertical program to test the concurrency as
class Vertical {
private int alt;
public synchronized void up() {
System.out.println(Thread.currentThread().getName()+" executing up() "+alt);
try{
Thread.sleep(1000);
}
catch(InterruptedException e){}
++alt;
System.out.println(Thread.currentThread().getName()+" ending up() "+alt);
}
public void down() {
--alt;
}
public synchronized void jump() {
int a = alt;
up();
down();
}
}
to see if the synchronised method up() is being executed by two threads concurrently
now to execute this i wrote:
public class test{
public static void main(
String[] args){
final Vertical v = new Vertical();
Runnable r = new Runnable(){
public void run(){
while(true){
v.up();v.down();v.jump();
}
}
};
Thread T1 = new Thread(r);
Thread T2 = new Thread(r);
T1.start();
T2.start();
}
}
when i saw the results i got this:
Thread-1 executing up() 0
Thread-1 ending up() 1
Thread-2 executing up() 1
Thread-2 ending up() 1
Thread-1 executing up() 0
Thread-1 ending up() 1
Thread-2 executing up() 0
Thread-2 ending up() 1
Thread-1 executing up() 0
Thread-1 ending up() 1
Thread-2 executing up() 1
Thread-2 ending up() 1
Thread-1 executing up() 1
....
there is no concurrent execution of up(). but if I changed the code in Vertical to include the System.out.... stmts in non synchronized down() i got:
Thread-1 executing down() 1
Thread-2 executing down() 2
Thread-1 ending down() 1
Thread-1 executing down() 2
Thread-2 ending down() 1
Thread-1 ending down() 0
Thread-2 executing down() 1
Thread-2 ending down() 0
Thread-1 executing down() 1
Thread-2 executing down() 2
Thread-2 ending down() 1
Thread-2 executing down() 2
Thread-1 ending down() 1
Thread-2 ending down() 0
Thread-1 executing down() 1this is being executed by two thread T1 and T2.as seen from first two output lines.
i dont think the answers given by Khalid are correct .Please clearify