package edu.wtbu;标签:同步,synchronized,Thread,代码,buyTicket,new,方法,public From: https://www.cnblogs.com/123456dh/p/17229756.html
//不安全的买票
public class Demo08 {
public static void main(String[] args) {
buyTicket buyTicket = new buyTicket();
new Thread(buyTicket,"我").start();
new Thread(buyTicket,"你").start();
new Thread(buyTicket,"黄牛党").start();
}
}
class buyTicket implements Runnable{
private int ticketNums=10;//票
boolean flag=true;//外部停止方式
@Override
public void run() {
//买票
while (flag){
try {
//模拟延时
Thread.sleep(1000);
buy();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
//synchronized 同步方法,锁的是this
public synchronized void buy() throws InterruptedException {
//判断是否有票
if(ticketNums<=0){
flag=false;
return;
}
//买票
System.out.println(Thread.currentThread().getName()+"拿到了"+ticketNums--);
}
}
/*synchronized代码块
synchronized(obj){
*/