synchronized是可重入锁,当运行线程处于阻塞状态,其他线程可以获得该线程锁定资源
public class Demo1 implements Runnable{
private int count = 50;
public void run() {
while (true){
synchronized(/*锁*/demo1.class){
if(count <= 0){
return;
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "买了第" + count-- + "张票");
}
}
}
}
public class Test {
public static void main(String[] args) {
demo1 p1 = new demo1();
Thread zhangsan = new Thread(p1, "张三");
Thread lisi = new Thread(p1, "李四");
Thread huangniu = new Thread(p1, "黄牛");
zhangsan.start();
lisi.start();
huangniu.start();
}
}