private int tickets = 100;
Object obj = new Object();
@Override
public void run() {
while (true) {
// synchronized (obj) {
// if (tickets > 0) {
// try {
// Thread.sleep(10);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// System.out.println(Thread.currentThread().getName() + "卖出第"
// + (tickets--) + "票");
// }
// }
show();
}
}
public synchronized void show() {
if (tickets > 0) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "卖出第"
+ (tickets--) + "票");
}
}
同步方法 的锁是this 同步代码块的锁可以任意
|