public class SellTicket {
public static void main(String[] args) {
SellTicke01 sellTicke01 = new SellTicke01();
SellTicke01 sellTicke02 = new SellTicke01();
SellTicke01 sellTicke03 = new SellTicke01();
Thread thread1 = new Thread(sellTicke01);
Thread thread2 = new Thread(sellTicke02);
Thread thread3 = new Thread(sellTicke03);
thread1.start();
thread2.start();
thread3.start();
}
}
class SellTicke01 implements Runnable {
static boolean loop = true;
static int ticketSum = 0;
static public synchronized void sell() {
// for (int i = 0; i < 100; i++) {
if (ticketSum == 30000) {
loop = false;
return;
}
System.out.println(Thread.currentThread().getName() + " " + (++ticketSum));
// try {
// Thread.sleep(1);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
}
@Override
public void run() {
while (loop) {
sell();
// try {
// Thread.sleep(10);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
}
}
}
是的。当一个线程获取锁资源的时候,其他线程就处于等待中,直到同步方法执行完毕后,才继续抢占资源。
对于普通同步方法,锁的是当前实例对象,通常指this,具体的一个个new Class(); 所有的普通同步方法用的都是同一把锁:实例对象本身
对于静态同步方法,锁的是当前类的Class模板,Class模板只有一个,一个Class模板可以new出多个Class对象
对于同步方法块, 锁的是synchronized括号内的对象