package com.lyon.demo.test.mayi;
public class Demo4 {
public static void main(String[] args) {
ThreadTrain4 th = new ThreadTrain4();
Thread thread = new Thread(th);
Thread thread1 = new Thread(th);
Thread thread2 = new Thread(th);
thread.start();
thread1.start();
thread2.start();
}
}
/**
* 功能描述:(多线程之买火车票案例-使用多线程同步代码解决线程安全问题)
*/
class ThreadTrain4 implements Runnable{
private static int count = 100;
// 自定义多线程同步锁
private Object mutex = new Object();
@Override
public void run() {
//同步锁放在这个位置,只能有一个线程执行
//synchronized (mutex){
while (count > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
sale();
}
}
//静态方法加锁 ThreadTrain4.class 或者getClass()方法
public static void sale() {
synchronized (ThreadTrain4.class){
//同步锁,串行化执行的时候,一定要做对应的逻辑判断
if(count > 0){
try {
//一旦加锁,sleep睡眠也不会释放锁
Thread.sleep(40);
} catch (InterruptedException e) {
e.printStackTrace();
}
//锁具体资源
System.out.println("窗口"+Thread.currentThread().getName()+"买了票"+count--);
}
}
}
}