class Ticket implements Runnable {
int num = 200;
boolean flag = true;
public void run() {
if (flag) {
while (true) {
synchronized (this) { //這里要和show方法同步的鎖(對象)保持一致登夫,實現(xiàn)同一共享數(shù)據(jù)功咒。
if (num > 0) {
System.out.println(Thread.currentThread().getName() + "----" + num--);
}
}
}
} else {
while (true) {
show();
}
}
}
public synchronized void show() {
if (num > 0) {
System.out.println(Thread.currentThread().getName() + "---.............." + num--);
}
}
}
class Demo1 {
public static void main(String[] args) {
Ticket t = new Ticket();
Thread tt = new Thread(t);
Thread ttt = new Thread(t);
tt.start();
t.flag = false;
ttt.start();
}
}
我們這里將另一個線程在show方法中執(zhí)行跋理,當方法里的所有代碼都需要同步時震放,可以在方法中直接加synchronized。
非靜態(tài)的方法在執(zhí)行的時候需要被對象調(diào)用幻捏。所以它用的對象就是this盆犁,this代表當前對象。
靜態(tài)的方法在執(zhí)行時用當前class文件代表對象篡九。