public class Mythread extends Thread {
// 使用多线程 实现3个售票窗口 卖100张票。
//定义变量保存票数
private static int num = 100;
Object obj = new Object();
public Mythread() {
}
public Mythread(int num) {
this.num = num;
}
@Override
public void run() {
while (true) {
synchronized (obj) {
if (num > 0) {
System.out.println(Thread.currentThread().getName() + "窗口,售出票数为" + num);
num--;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public class Test01 {
public static void main(String[] args) {
// 26.多线程
// 使用多线程 实现3个售票窗口 卖100张票。
// 每售一张票,打印 “X号窗口出票成功,现在余票X张”
Mythread m1=new Mythread();
Thread t1=new Thread(m1,“张三”);
Thread t2=new Thread(m1,“李四”);
Thread t3=new Thread(m1,“王五”);
//调用开启方法
t1.start();
t2.start();
t3.start();
}
}