ได้ เราสามารถ synchronized เมธอด run() ใน Java ได้ แต่ไม่จำเป็น เพราะเมธอดนี้ถูกเรียกใช้โดยเธรดเดียวเท่านั้น ดังนั้น การ synchronize จึงไม่จำเป็นสำหรับเมธอด run() ควร synchronize เมธอด non-static ของคลาสอื่นแทน เพราะอาจถูกเรียกโดยหลายเธรดพร้อมกัน
ตัวอย่าง
public class SynchronizeRunMethodTest implements Runnable {
public synchronized void run() {
System.out.println(Thread.currentThread().getName() + " is starting");
for(int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + " is running");
} catch(InterruptedException ie) {
ie.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + " is finished");
}
public static void main(String[] args) {
SynchronizeRunMethodTest test = new SynchronizeRunMethodTest();
Thread t1 = new Thread(test);
Thread t2 = new Thread(test);
t1.start();
t2.start();
}
}
ผลลัพธ์
Thread-0 is starting Thread-0 is running Thread-0 is running Thread-0 is running Thread-0 is running Thread-0 is running Thread-0 is finished Thread-1 is starting Thread-1 is running Thread-1 is running Thread-1 is running Thread-1 is running Thread-1 is running Thread-1 is finished