public class Demo {
public static void main(String[] args) {
//1.实例化一个票池;
Tickets tic = new Tickets();
//2.实例化三个线程,模拟三个窗口售票
MyThread t1 = new MyThread(tic);
MyThread t2 = new MyThread(tic);
MyThread t3 = new MyThread(tic);
//3.设置线程名称
t1.setName("窗口1");
t2.setName("窗口2");
t3.setName("窗口3");
//4.启动线程
t1.start();
t2.start();
t3.start();
}
}
import java.util.TreeSet;
public class MyThread extends Thread{
private Tickets tic;
private int count;
private TreeSet<Integer> tree = new TreeSet<>();
public MyThread(Tickets t){ 这个构造方法的作用在哪里?
this.tic = t; 求解这里为什么要用This?
};
public void run() {
while(true){
int t = this.tic.getTicket();
if(t > 0){
// System.out.println(this.getName() + " 抢到票:" + t);
tree.add(t); 票池里面已经有了此方法,为什么还要继续写?
}else{
// System.out.println("没票了,不抢了");
break;
}
}
System.out.println(this.getName() + " 共抢到 : " + tree.size() + " 张票,明细:" + tree);
}
}
public class Tickets {
private int ticketNo = 100;
public int getTicket(){//窗口1
synchronized (this) {
if(this.ticketNo > 0){//窗口1
return this.ticketNo--;//窗口1
}else{
return 0;
}
}
}
}
|
|