Java多线程购票

售票系统

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("不好意思,票已经售完~~");
        }
    }

    @Override
    public void run() {
        if (ticketNumber > 0) {
            sale();
        }
    }
}


main函数

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();
        }
    }



}

你可能感兴趣的:(Java多线程购票)