I made a few changes to your code and it looks like this now.
class shared {
static int i=0;
synchronized static void print(long id) {
System.out.println("print() called from thread id :"+id+", i ="+i);
i++;
}
synchronized void display(int id) {
System.out.println("display() called from thread id :"+id+", i = "+i);
i--;
}
}
class thread1 extends Thread {
int i=0,id=1;
shared s;
thread1(shared s) {
this.s =s;
}
public void run() {
try {
while( i < 50 ) {
Thread.sleep(100);
s.print(id);
i++;
}
} catch(Exception e) {
}
}
}
//
class thread2 extends Thread {
int i=0,id=2;
shared s;
thread2(shared s) {
this.s =s;
}
public void run() {
try {
while( i < 50 ) {
Thread.sleep(100);
s.display(id);
i++;
}
} catch(Exception e) {
}
}
}
//
public class TestA {
static void main(String[] args) {
shared s = new shared();
thread1 t1 = new thread1(s);
thread2 t2 = new thread2(s);
t1.start();
t2.start();
}
}
This code works and keeps printing:
print() called from thread id :1, i =0
display() called from thread id :2, i = 1
print() called from thread id :1, i =0
display() called from thread id :2, i = 0
display() called from thread id :2, i = 0
print() called from thread id :1, i =-1
display() called from thread id :2, i = 0
print() called from thread id :1, i =0
display() called from thread id :2, i = 0
print() called from thread id :1, i =-1
display() called from thread id :2, i = 0
print() called from thread id :1, i =-1
display() called from thread id :2, i = 0
print() called from thread id :1, i =-1
display() called from thread id :2, i = 0
print() called from thread id :1, i =0
display() called from thread id :2, i = 0
print() called from thread id :1, i =-1
display() called from thread id :2, i = 0
print() called from thread id :1, i =0
print() called from thread id :1, i =0
display() called from thread id :2, i = 1
------------------
Cheers,
Manoj (
http://www7.brinkster.com/manoj9/)