package com.harenmu.homework;
public class CustomerRunable implements Runnable{
private Tickets tickets;
public CustomerRunable(Tickets tickets) {
this.tickets = tickets;
}
@Override
public void run() {
tickets.buyTickets(1);
System.out.println(Thread.currentThread().getName() + "购票成功,余票: " + tickets.getAllowance());
}
}
package com.harenmu.homework;
public class Tickets {
private int allowance;
public Tickets(int allowance) {
this.allowance = allowance;
}
public int getAllowance() {
return allowance;
}
public void setAllowance(int allowance) {
this.allowance = allowance;
}
public void buyTickets(int num){
synchronized (this){
int before = this.allowance;
int after = before - num;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.setAllowance(after);
}
}
}
package com.harenmu.homework;
public class CustomerTest {
public static void main(String[] args) {
Tickets tickets = new Tickets(100);
CustomerRunable[] customerRunables = new CustomerRunable[100];
Thread[] threads = new Thread[100];
for (int i = 0; i < customerRunables.length; i++) {
customerRunables[i] = new CustomerRunable(tickets);
}
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(customerRunables[i]);
threads[i].start();
}
}
}