窗口抢票简单实现
package com.gao.Project.Pro7;
public class BuyTicketThread extends Thread{
//有参构造器
public BuyTicketThread(String name){
super(name);//调用父类构造器传名字
}
//一共10张票
static int ticketNum = 10; //多个对象共享10张票
//每个窗口都是一个线程对象:每个对象执行的代码放入run方法中
@Override
public void run() {
//每个窗口后面都有100个人在抢票
for (int i = 1; i<=100; i++) {
if(ticketNum > 0){//对票数进行判断
System.out.println("我在"+this.getName()+"买到了北京到哈尔滨的第"+ ticketNum-- +"张车票");
}
}
}
}
package com.gao.Project.Pro7;
public class Test {
public static void main(String[] args) {
//多个窗口抢票:三个窗口--->三个线程对象
BuyTicketThread t1 = new BuyTicketThread("窗口1");
t1.start();
BuyTicketThread t2 = new BuyTicketThread("窗口2");
t2.start();
BuyTicketThread t3 = new BuyTicketThread("窗口3");
t3.start();
}
}
多次运行会出现错误错误:例如同一张票重复被购买,出现0票负数票等问题
窗口抢票加强版
package com.gao.Project.Pro8;
public class BuyTicketThread implements Runnable {//实现Runnable接口
int ticketNum = 10;
@Override
public void run() {
for (int i = 1; i <100 ; i++) {
if (ticketNum>0){
System.out.println("我在窗口"+Thread.currentThread().getName()+ "买到了北京到哈尔滨的第"+ ticketNum-- +"张车票");
}
}
}
}
package com.gao.Project.Pro8;
import java.util.concurrent.TransferQueue;
public class Test {
public static void main(String[] args) {
//定义一个线程对象
BuyTicketThread bt = new BuyTicketThread();
//窗口1买票
Thread bt1 = new Thread(bt,"窗口1");
bt1.start();
//窗口2买票
Thread bt2 = new Thread(bt,"窗口2");
bt2.start();
//窗口3买票
Thread bt3 = new Thread(bt,"窗口3");
bt3.start();
}
}
标签:窗口,Thread,start,new,题目,BuyTicketThread,public,火车票
From: https://www.cnblogs.com/gaoxiaocuo/p/16768761.html