package deep;标签:Thread,start,Window3,安全,线程,解决,new,ticket,public From: https://www.cnblogs.com/liujy2233/p/16883987.html
//同步方法
class Window3 implements Runnable {
private int ticket = 100;
public void run() {
while (true) {
show();
}
}
private synchronized void show() {
if (ticket > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":卖票:票号为:" + ticket);
ticket--;
}
}
}
public class WindowTest3 {
public static void main(String[] args) {
Window3 w = new Window3(); //创建一个对象
Thread t1 = new Thread(w); //三个构造器使用同一个对象
Thread t2 = new Thread(w);
Thread t3 = new Thread(w);
t1.setName("窗口1");
t2.setName("窗口2");
t3.setName("窗口3");
t1.start();
t2.start();
t3.start();
}
}