การทำให้ Instance lock พร้อมให้ thread แต่ล่ะตัวทำงานเสร็จก่อน ตัวถัดไปถึงจะทำงานได้
1.ทำงานได้หลาย Thread
public class TestClassUnSyn extends Thread {
public TestClassUnSyn(String s) {
super(s);
}
public synchronized void run() {
String t = Thread.currentThread().getName();
System.out.println(t + " : " + "enter f()");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
//
}
System.out.println(t + " : " + "leaving f()");
}
public static void main(String[] args) throws Exception {
String[] nameThread = { "A", "B", "C", "D", "E" };
for (int i = 0; i < 5; i++) {
new TestClassUnSyn(nameThread[i]).start();
}
}
}
*** output ****
A : enter f()
B : enter f()
C : enter f()
D : enter f()
E : enter f()
C : leaving f()
B : leaving f()
A : leaving f()
E : leaving f()
D : leaving f()
2.ทำงานได้ทีละ Thread
public class TestClassSyn extends Thread {
public TestClassSyn(String s) {
super(s);
}
public void run() {
synchronized (TestClassSyn.class) {
String t = Thread.currentThread().getName();
System.out.println(t + " : " + "enter f()");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
//
}
System.out.println(t + " : " + "leaving f()");
}
}
public static void main(String[] args) throws Exception {
String[] nameThread = { "A", "B", "C", "D", "E" };
for (int i = 0; i < 5; i++) {
new TestClassSyn(nameThread[i]).start();
}
}
}
**** output ****
A : enter f()
A : leaving f()
E : enter f()
E : leaving f()
D : enter f()
D : leaving f()
C : enter f()
C : leaving f()
B : enter f()
B : leaving f()