package com.tju.couur;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.ArrayList;
/**
* Created by xiangyang.laixiang on 2016/8/8.
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class TicketSaleSystem implements Runnable {
@Setter
private Person person;
private volatile int ticketNumber = 10;
public synchronized void sale() {
if (ticketNumber > 0) {
ticketNumber--;
System.out.println(
Thread.currentThread().getName() + "獲得一張票," + person.getTicketName() + "剩余:"
+ ticketNumber);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
System.out.println(ticketNumber);
System.out.println("不好意思,票已經(jīng)售完~~");
}
}
@Override
public void run() {
if (ticketNumber > 0) {
sale();
}
}
}
main函數(shù)
package com.tju.couur;
/**
* Created by xiangyang.laixiang on 2016/8/8.
*/
public class Main {
private static TicketSaleSystem myTicketThread = new TicketSaleSystem();
public static void main(String args[]) throws InterruptedException {
for (int i=0;i<100;i++)
{
Person personInfo = new Person("用戶"+i,i+"");
myTicketThread.setPerson(personInfo);
Thread myThread = new Thread( myTicketThread,"售票窗口"+i);
myThread.start();
}
}
}