//火车站售票,票有个成员记录自己的票数,
class Ticket{
private int num;
private static Ticket instance= null;
public static Ticket getInstance(int num){
if(instance == null){
instance = new Ticket(num);
}
return instance;
}
private Ticket(int num){
this.num = num;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public synchronized void sale(){
if(this.num > 0){
System.out.println(Thread.currentThread().getName()+"卖出了一张票");
this.num--;
System.out.println("还有: "+num+" 张票!");
}
}
}
class SaleTicket implements Runnable{
private Ticket ticket;
public SaleTicket(int num){
this.ticket = Ticket.getInstance(num);
}
public void run() {
while(ticket.getNum() > 0){
ticket.sale();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class TestSaleTicket {
public static void main(String[] args) {
SaleTicket ticket = new SaleTicket(20);
new Thread(ticket,"甲--->").start();
new Thread(ticket,"乙--->").start();
new Thread(ticket,"丙--->").start();
}
}
//火车站售票,票有个成员记录自己的票数,
class SaleTicket implements Runnable{
private int num;
public SaleTicket(int num){
this.num = num;
}
public void run() {
while(this.num > 0){
sale();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public synchronized void sale(){
if(this.num > 0){
System.out.println(Thread.currentThread().getName()+"卖出了一张票");
this.num--;
System.out.println("还有: "+num+" 张票!");
}
}
}
public class TestSaleTicket {
public static void main(String[] args) {
SaleTicket ticket = new SaleTicket(20);
new Thread(ticket,"甲--->").start();
new Thread(ticket,"乙--->").start();
new Thread(ticket,"丙--->").start();
}
}