线程不安全三大问题_解决 同步方法及同步块
2021-02-02 16:16
标签:new trace owa cat inter one nts while extends 线程不安全三大问题_解决 同步方法及同步块 标签:new trace owa cat inter one nts while extends 原文地址:https://www.cnblogs.com/liqiliang1437/p/12807981.htmlpackage com.qiliang.demo13_线程同步安全;
// 线程同步安全问题 , 卖票案例演示
public class UnSafeBuyTicket {
public static void main(String[] args) {
BuyTicket station = new BuyTicket();
new Thread(station,"小A").start();
new Thread(station,"小B").start();
new Thread(station,"黄牛党").start();
}
}
class BuyTicket implements Runnable{
// 定义票数
private int ticketNums = 10;
// 线程停止的标志位
boolean flag = true;
@Override
public void run() {
// 买票
while (flag){
buy();
}
}
// synchronized 同步方法
private synchronized void buy() {
// 判断是否有票
if(ticketNums list = new ArrayList();
for (int i = 0; i {
synchronized (list){
list.add(Thread.currentThread().getName());
}
}).start();
}
Thread.sleep(3000); // 9997 i=10000
System.out.println(list.size()); // 918 i=1000
}
}
文章标题:线程不安全三大问题_解决 同步方法及同步块
文章链接:http://soscw.com/index.php/essay/50040.html