package cn.itcast.day26_Prictice;
/**
* 编写程序,完成模拟3个窗口共卖100张票的程序,并测试。
* 关键是: 锁,放的位置
*/
public class Prictice2 {
public static void main(String[] args) {
// 创建一个runnable接口的子类
TicketsWindow tw = new TicketsWindow();
// 创建一个线程对象
Thread window1 = new Thread(tw);
window1.setName("1窗口");
Thread window2 = new Thread(tw);
window2.setName("2窗口");
Thread window3 = new Thread(tw);
window3.setName("3窗口");
// 窗口开始卖票了
window1.start();
window2.start();
window3.start();
}
}
另一个类:
package cn.itcast.day26_Prictice;
public class TicketsWindow implements Runnable {
static int tickeks = 100;
@Override
public void run() {
for (int i = 1; i <= 100; i++) {
// 锁,解决线程不安全问题
synchronized (this) {
if(tickeks == 0) {
System.out.println(Thread.currentThread().getName()+"没票了...");
break;
} else {
System.out.println(Thread.currentThread().getName() + "正在卖票啦.." + "第" + (100-tickeks+1) + "张票..");
tickeks--;
}
}
}
}
}
|
|