利用java定义一个票池有10张票分别利用懒汉式饿汉式静态内部类三种方式实现单例模式设计写出测试类分别用两个线程完成对票池的出票操作
- 懒汉式
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();
}
}
- 饿汉式
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();
}
}
- 静态内部类
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();
}
}
原文地址: https://www.cveoy.top/t/topic/bEO3 著作权归作者所有。请勿转载和采集!