public class Test {
public static void main(String[] args) {
sample obj = new sample();
t1 tt1 = new t1(obj);
t2 tt2 = new t2(obj);
tt1.start();
tt2.start();
}
}
//It’s possible that both static synchronized and non static synchronized method can run simultaneously or concurrently because they lock on different object.
class sample{
public synchronized static void m1(String name){
System.out.println(name+":m1");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public synchronized void m2(String name){
System.out.println(name+":m2");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class t1 extends Thread{
sample s;
t1(sample s){
this.s =s;
}
@Override
public void run() {
s.m1(Thread.currentThread().getName());
s.m2(Thread.currentThread().getName());
}
}
class t2 extends Thread{
sample s;
t2(sample s){
this.s =s;
}
@Override
public void run() {
s.m2(Thread.currentThread().getName());
s.m1(Thread.currentThread().getName());
}
}
output:
Thread-1:m2
Thread-0:m1
wait 2 second
Thread-0:m2
Thread-1:m1
or
Thread-0:m1
Thread-1:m2
wait 2 second
Thread-0:m2
Thread-1:m1
No comments:
Post a Comment