线程安全方式1Thread类---同步代码块

/**
* 基于Thread类的线程安全问题1---同步代码块方式
*
* @Author: ITYW
* @Create 2020 - 10 - 26 - 18:35
*/
public class ThreadSecurity02 {
public static void main(String[] args) {
Thread_Security02 t1 = new Thread_Security02();
Thread_Security02 t2 = new Thread_Security02();
Thread_Security02 t3 = new Thread_Security02();

t1.setName("窗口1");
t2.setName("窗口2");
t3.setName("窗口3");

t1.start();
t2.start();
t3.start();

}
}
class Thread_Security02 extends Thread{
private static int ticket = 100;
@Override
public void run() {
while (true){
synchronized (Thread_Security02.class){
if (ticket > 0){
System.out.println(Thread.currentThread().getName()+"卖出了第"+ticket+"张");
ticket--;
}else {
break;
}
}
}
}
}
原文地址:https://www.cnblogs.com/ITYW/p/13880467.html