package com.zl.thread;
/**
* @author zhanglei
* @description : 模拟两个线程抢火车票场景
* @date 2021/3/26$ 14:29$
* @return $
*/
class HcThread implements Runnable{
private int count = 100;
private Object suo = new Object();
public void run() {
try{
Thread.sleep(50);
}catch (Exception e){
e.printStackTrace();
}
while(count > 0){
synchronized (suo){
if(count > 0){
System.out.println(Thread.currentThread().getName()+"出售第"+(100-count+1)+"张票");
count--;
}
}
}
}
}
public class threadDemo {
public static void main(String[] args) {
HcThread hc = new HcThread();
Thread t1 = new Thread(hc,"窗口1");
Thread t2 = new Thread(hc,"窗口2");
t1.start();
t2.start();
}
}
synchronized修饰方法为同步函数==synchronized(this),实际上是this锁
static synchronized 静态同步函数的锁为synchronized(class),字节码锁
线程安全是指多个线程同时对全局变量进行写操作,产生的数据问题。