同步块
package cn.ljz.cn.ljz.terminalThread;
/**
* Created by LIN on 2019/3/3.
*/
public class BuyTicketTest {
public static void main(String[] args) {
Syn12306Web web = new Syn12306Web(10);
new Thread(web, "lin").start();
new Thread(web, "Mary").start();
new Thread(web, "Sofia").start();
}
}
class Syn12306Web implements Runnable {
int ticketNum;
boolean flag = true;
Syn12306Web(int ticketNum) {
this.ticketNum = ticketNum;
}
//数据安全:考虑数据完整性,不是代码完整性
public void test() {
//考虑没票的情况(个人认为:可能被优化到,但是也可能没有被优化到)
if (ticketNum <= 0) {
flag = false;
return;
}
//考虑正常情况和最后一张票的情况
synchronized (this) {
if (ticketNum <= 0) {
flag = false;
return;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "-->" + ticketNum--);
}
}
@Override
public void run() {
while (flag) {
test();
}
}
}
网友评论