package ch12;
public class thredTest implements Runnable {
private int tinckNum = 10;
boolean flog = true;
@Override
public void run() {
while (flog) {
// 线程睡眠
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
buy();
}
}
// synchromized关键字给buy对象上锁
public synchronized void buy() {
// 线程关闭
if (tinckNum <= 0) {
flog = false;
return;
}
System.out.println(Thread.currentThread().getName() + "-----拿到了第" + tinckNum-- + "票!--");
}
public static void main(String[] args) {
thredTest test = new thredTest();
// 三个线程
new Thread(test, "1号线程").start();
new Thread(test, "2号线程").start();
new Thread(test, "3号线程").start();
}
}