/**
* 票类
* @author 2018121205
*
*/
public class Ticket {
public int ticket = 100;//100张票
/**
* 买票的方法
* @param id
*/
public synchronized void paye(int id){
//判读是否还有票买
if(!(ticket == 0)){
//打印买票信息
System.out.println("第" + ticket + "张票被卖出," + "买票线程:" + id);
//自身递减
ticket --;
} else {
//如果票买完了就结束调线程的使命
Thread.currentThread().stop();
}
}
}
/**
* 人类 负责买票
* @author 2018121205
*
*/
class Person implements Runnable{
//保存票对象
public Ticket ticket;
//线程id
public int id;
/**
* 带参数构造方法 参数化参数
* @param ticket
* @param id
*/
public Person(Ticket ticket, int id) {
this.ticket = ticket;
this.id = id;
}
@Override
public void run() {
// TODO Auto-generated method stub
//循环买票
while(true){
try {
Thread.currentThread().sleep(100);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ticket.paye(id);
}
}
}
/**
* 程序入口
* @author 2018121205
*
*/
public class Dome {
public static void main(String[] args) {
//票100张
Ticket ticket = new Ticket();
//三个人去买票
new Thread(new Person(ticket, 1)).start();
new Thread(new Person(ticket, 2)).start();
new Thread(new Person(ticket, 3)).start();
}
}