练习:使用两个不同的线程类实现买票系统
请创建两个不同的线程类、一个测试类以及一个票的管理类。
其中票的管理类用于储存票的数量。两个线程类看作不同的买票方式。
步骤:
1、创建所需的类
App售票线程类
public class Runnable_AppTicketSeller implements Runnable{
@Override
public void run() {
}
}
Web售票线程类
public class Runnable_WebTicketSeller implements Runnable{
@Override
public void run() {
}
}
买票测试类
public class BuyTicket {
public static void main(String[] args) {
Runnable_AppTicketSeller ra = new Runnable_AppTicketSeller();
Runnable_WebTicketSeller rb = new Runnable_WebTicketSeller();
Thread tApp = new Thread(ra,"App售票");
Thread tWeb = new Thread(rb,"Web售票");
tApp.start();
tWeb.start();
}
}
票务管理类
public class TicketMgr {
public static int count = 100;
}
2、编写两个售票类
在两个run()中加入:
while (true){
if(TicketMgr.count>0){
System.out.println(Thread.currentThread().getName()+"卖出第"+TicketMgr.count+"张票");
TicketMgr.count--;
}else break;
}
我们需要在这添加线程锁。
但是我们现在是两个不同的线程类,按照以前的方法是不行的。
我们可以在售票处构造一个lock,然后传进两个线程类中。
那么我们要为两个线程类添加一个构造方法,传入同一个lock锁。
售票类:
public class BuyTicket {
public static void main(String[] args) {
Object lock = new Object();
Runnable_AppTicketSeller ra = new Runnable_AppTicketSeller(lock);
Runnable_WebTicketSeller rb = new Runnable_WebTicketSeller(lock);
Thread tApp = new Thread(ra,"App售票");
Thread tWeb = new Thread(rb,"Web售票");
tApp.start();
tWeb.start();
}
}
两个线程类:
public class Runnable_AppTicketSeller implements Runnable{
Object lock;
public Runnable_AppTicketSeller(Object lo){
lock = lo;
}
@Override
public void run() {
while (true){
synchronized (lock) {
if (TicketMgr.count > 0) {
System.out.println(Thread.currentThread().getName() + "卖出第" + TicketMgr.count + "张票");
TicketMgr.count--;
} else break;
}
}
}
}
public class Runnable_WebTicketSeller implements Runnable{
Object lock;
public Runnable_WebTicketSeller(Object lo){
lock = lo;
}
@Override
public void run() {
while (true){
synchronized (lock) {
if (TicketMgr.count > 0) {
System.out.println(Thread.currentThread().getName() + "卖出第" + TicketMgr.count + "张票");
TicketMgr.count--;
} else break;
}
}
}
}
3、简化代码
public class BuyTicket {
public static void main(String[] args) {
Object lock = new Object();
Runnable_AppTicketSeller ra = new Runnable_AppTicketSeller(lock);
Runnable_WebTicketSeller rb = new Runnable_WebTicketSeller(lock);
new Thread(ra,"App售票").start();
new Thread(rb,"Web售票").start();
}
}
完成✅