多线程卖票程序
下面展示一些 代码片
。
//资源类
class Ticket{
private int number = 50;
ReentrantLock lock = new ReentrantLock();
public void sale(){
lock.lock();
try {
if (number > 0){
System.out.println(Thread.currentThread().getName()+"卖出第:\t"
+(number--)+"\t 还剩下:" +number);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
//多线程卖票
public class SaleTicketDemo {
public static void main(String[] args) {
Ticket ticket = new Ticket();
new Thread(()->{
for (int i = 0; i <= 50; i++) {
ticket.sale();
}
},"a").start();
new Thread(()->{
for (int i = 0; i <= 50; i++) {
ticket.sale();
}
},"b").start();
new Thread(()->{
for (int i = 0; i <= 50; i++) {
ticket.sale();
}
},"c").start();
new Thread(()->{
for (int i = 0; i <= 50; i++) {
ticket.sale();
}
},"d").start();
}
}