1. 程式人生 > 實用技巧 >多執行緒,同步程式碼塊。

多執行緒,同步程式碼塊。

public class Demo07 {
public static void main(String[] args) {
final Printer p = new Printer();
new Thread() {
public void run() {
while (true) {
p.print1();
}
}
}.start();
}

static class Printer {
Demo01 d = new Demo01();

public void print1() {
synchronized (d) { //鎖物件不能用匿名物件,因為匿名物件不是同一個物件;同步程式碼塊 ,鎖機制,鎖物件可以是任意的物件。
System.out.print("黑");
System.out.print("馬");
System.out.print("程");
System.out.print("序");
System.out.print("員");
System.out.print("\r\n");
}
}

public void print2() {
synchronized (d) {
System.out.print("傳");
System.out.print("智");
System.out.print("播");
System.out.print("客");
System.out.print("\r\n");
}
}

}
}