Java单例模式实现票池:懒汉式、饿汉式、静态内部类
Java单例模式实现票池:懒汉式、饿汉式、静态内部类
本文将使用Java语言,通过定义一个包含10张票的票池,分别利用懒汉式、饿汉式、静态内部类三种方式实现单例模式,并编写测试类模拟两个线程同时进行售票操作,演示单例模式在多线程场景下的应用。
1. 懒汉式
public class TicketPool {
private static TicketPool instance;
private int count = 10;
private TicketPool() {}
public static TicketPool getInstance() {
if (instance == null) {
synchronized (TicketPool.class) {
if (instance == null) {
instance = new TicketPool();
}
}
}
return instance;
}
public synchronized boolean sellTicket() {
if (count <= 0) {
return false;
}
count--;
return true;
}
}
测试类:
public class TestTicketPool {
public static void main(String[] args) {
TicketPool pool = TicketPool.getInstance();
Runnable runnable = new Runnable() {
@Override
public void run() {
synchronized (pool) {
while (pool.sellTicket()) {
System.out.println(Thread.currentThread().getName() + '卖出了一张票,还剩' + pool.count + '张');
}
}
}
};
Thread t1 = new Thread(runnable, '窗口1');
Thread t2 = new Thread(runnable, '窗口2');
t1.start();
t2.start();
}
}
2. 饿汉式
public class TicketPool {
private static TicketPool instance = new TicketPool();
private int count = 10;
private TicketPool() {}
public static TicketPool getInstance() {
return instance;
}
public synchronized boolean sellTicket() {
if (count <= 0) {
return false;
}
count--;
return true;
}
}
测试类:
public class TestTicketPool {
public static void main(String[] args) {
TicketPool pool = TicketPool.getInstance();
Runnable runnable = new Runnable() {
@Override
public void run() {
synchronized (pool) {
while (pool.sellTicket()) {
System.out.println(Thread.currentThread().getName() + '卖出了一张票,还剩' + pool.count + '张');
}
}
}
};
Thread t1 = new Thread(runnable, '窗口1');
Thread t2 = new Thread(runnable, '窗口2');
t1.start();
t2.start();
}
}
3. 静态内部类
public class TicketPool {
private int count = 10;
private TicketPool() {}
private static class TicketPoolHolder {
private static final TicketPool INSTANCE = new TicketPool();
}
public static TicketPool getInstance() {
return TicketPoolHolder.INSTANCE;
}
public synchronized boolean sellTicket() {
if (count <= 0) {
return false;
}
count--;
return true;
}
}
测试类:
public class TestTicketPool {
public static void main(String[] args) {
TicketPool pool = TicketPool.getInstance();
Runnable runnable = new Runnable() {
@Override
public void run() {
synchronized (pool) {
while (pool.sellTicket()) {
System.out.println(Thread.currentThread().getName() + '卖出了一张票,还剩' + pool.count + '张');
}
}
}
};
Thread t1 = new Thread(runnable, '窗口1');
Thread t2 = new Thread(runnable, '窗口2');
t1.start();
t2.start();
}
}
通过以上三种方式实现的票池,可以有效地保证票池的单例特性,并利用synchronized关键字保证线程安全。在实际应用中,可以根据具体的场景选择最适合的单例模式实现方式。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/m815 著作权归作者所有。请勿转载和采集!