线程安全方式1Thread类---同步方法
1.继承Thread类的方式---同步方法(以卖票为例)
/**
* 基于Thread类的线程安全问题1---同步方法
*
* @Author: ITYW
* @Create 2020 - 10 - 26 - 18:16
*/
public class ThreadSecurity {
public static void main(String[] args) {
Thread_Security t1 = new Thread_Security();
Thread_Security t2 = new Thread_Security();
Thread_Security t3 = new Thread_Security();
t1.setName("window1");
t2.setName("window2");
t3.setName("window3");
t1.start();
t2.start();
t3.start();
}
}
class Thread_Security extends Thread{
private static int ticket = 10000;
@Override
public void run() {
while (true) {
sale();
}
}
public static synchronized void sale(){
if (ticket > 0) {
System.out.println(Thread.currentThread().getName() + "卖出第" + ticket + "张");
ticket--;
}
}
}