package com.atguigu.java;
import static java.lang.Thread.sleep;
/**
*使用同步方法解决实现Runnable接口的线程安全问题
*
* @author Dxkstart
* @create 2021-05-07 18:02
*/
public class WindowTest4 {
public static void main(String[] args) {
//3.创建实现类的对象
Window4 w1 = new Window4();
//4.将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象
Thread t1 = new Thread(w1);
Thread t2 = new Thread(w1);
Thread t3 = new Thread(w1);
//5.通过Thread类的对象调用start()
t1.setName("窗口一:");
t2.setName("窗口二:");
t3.setName("窗口三:");
t1.start();
t2.start();
t3.start();
}
}
// 1.创建一个实现Runnable接口的类
class Window4 implements Runnable {
private int ticket = 100;
//2.实现类去实现Runnable中的抽象方法:run()
@Override
public void run() {
while (true) {
show();
}
}
public synchronized void show(){//同步监视器:this
if (ticket > 0) {
try {
sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() +
"卖票,票号为:" + ticket);
ticket--;
}
}
}