Java多线程模拟售票系统

Java创建多线程的两种基本方法:

方法1.继承Thread类
(1)定义子类,继承Thread类,重写该类的run()方法作为线程执行体;
(2)创建该子类的实例作为线程对象;

(3)调用线程对象的start()方法来启动线程;

我们以模拟火车售票系统为例:

public class SellTicket {

	public static void main(String[] args) {
		for(int i=1; i<4; i++){
			TicketWindow tw = new TicketWindow();
			tw.setName("TicketWindow-" + i);
			tw.start();
		}
	}
}

class TicketWindow extends Thread{
	private int tickets = 100;//车票总量
	@Override
	public void run(){
		while(true){
			if(tickets>0){
				System.out.println(Thread.currentThread().getName() + "准备出票,剩余票数:" + tickets + "张");                    
                tickets--;                                                                                              
                System.out.println(Thread.currentThread().getName() + "卖出一张,剩余票数:" + tickets + "张");
                try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			else{
				System.out.println(Thread.currentThread().getName() + "余票不足,停止售票!");
				break;
			}
		}
	}
}

方法2.实现Runnable接口

(1)定义类实现Runnable接口,重写run()方法;
(2)创建该实现类的实例,以该实例作为Thread的target来创建Thread对象;

(3)调用该Thread对象的start()方法来启动该线程;

还是以模拟火车售票窗口为例:

public class SellTicket {

	public static void main(String[] args) {
		TicketWindow tw = new TicketWindow();
		for(int i=1; i<4; i++){
			Thread t = new Thread(tw,"TickWindow-" + i);
			t.start();
		}
	}
}

class TicketWindow implements Runnable{
	private int tickets = 100;//车票总量
	@Override
	public void run(){
		while(true){
			if(tickets>0){
				System.out.println(Thread.currentThread().getName() + "准备出票,剩余票数:" + tickets + "张");                    
                tickets--;                                                                                              
                System.out.println(Thread.currentThread().getName() + "卖出一张,剩余票数:" + tickets + "张");
                try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			else{
				System.out.println(Thread.currentThread().getName() + "余票不足,停止售票!");
				break;
			}
		}
	}
}

注意:

继承Thread类与实现Runnable接口的区别及优缺点对比:

继承Thread类实现Runnable接口
能否继承其他类不能
如何访问当前线程this即为当前线程Thread.currentThread()
是否共享同一target是,适合多个相同线程处理同一份资源的情况

因此,一般推荐采用实现Runnable接口/Callable接口的方式创建多线程;

虽然上面实现Runnable接口的火车售票系统共享了车票总数,但是没有控制同一时刻只能有一个线程进行卖票操作,因此需要同步关键字 synchronized 进行控制,

线程同步分为同步块和同步方法:

1.同步块

同步块的语法格式为:

synchronized(object){
    //...同步代码块
}

上述代码的意思是,要想执行同步代码块,必须先获得同步监视器的锁定.

其中object为同步监视器,一般使用可能被并发访问的共享资源当同步监视器;

下面给出java多线程模拟火车售票系统的同步块实现:

(1)通过extends Thread实现:由于卖票时生成了多个TicketWindow的多个实例,同步对象需要为TicketWindow的类变量或者静态变量

public class SellTicket {

    public static void main(String[] args) {
        for(int i=1; i<4; i++){
            TicketWindow ticketWindow = new TicketWindow();
            ticketWindow.setName("TickWindow0-" + i);
            ticketWindow.start();
        }
    }
}

class TicketWindow extends Thread{
    private static int tickets = 100;//车票总量
    //类静态变量,用作同步监视器
    private static Object monitor = new Object();

    @Override
    public void run(){
        while(true){
            //同步监视器,由于售票时创建了多个实现了Thread的子类的实例,此处必须使用字类的class对象,或者其静态变量等多个实例共享的变量
            synchronized (TicketWindow.class) {
                if(tickets>0){
                    System.out.println(Thread.currentThread().getName() + "准备出票,剩余票数:" + tickets + "张");
                    tickets--;
                    System.out.println(Thread.currentThread().getName() + "卖出一张,剩余票数:" + tickets + "张");
                    try {
                        //休眠100ms卖票完会报错ERROR: JDWP Unable to get JNI 1.2 environment, jvm->GetEnv() return code = -2JDWP exit error AGENT_ERROR_NO_JNI_ENV(183):  [../../../src/share/back/util.c:820]
                        //Thread.sleep(100);
                        Thread.sleep(500);//出票成功后让当前售票窗口睡眠,以便让其他售票窗口卖票
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                else{
                    System.out.println(Thread.currentThread().getName() + "余票不足,停止售票!");
                    break;
                }
            }
        }
    }
}

(2)通过implements Runnable实现:

	public static void main(String[] args) {
		TicketWindow tw = new TicketWindow();
		for(int i=1; i<4; i++){
			Thread t = new Thread(tw,"TickWindow-" + i);
			t.start();
		}
	}
}

class TicketWindow implements Runnable{
	private int tickets = 10;//车票总量
	@Override
	public void run(){
		while(true){
			synchronized (this) {
				if(tickets>0){
					System.out.println(Thread.currentThread().getName() + "准备出票,剩余票数:" + tickets + "张");                    
	                tickets--;                                                                                              
	                System.out.println(Thread.currentThread().getName() + "卖出一张,剩余票数:" + tickets + "张");
	                try {
	                	//休眠100ms卖票完会报错ERROR: JDWP Unable to get JNI 1.2 environment, jvm->GetEnv() return code = -2JDWP exit error AGENT_ERROR_NO_JNI_ENV(183):  [../../../src/share/back/util.c:820]
						//Thread.sleep(100);
						Thread.sleep(500);//出票成功后让当前售票窗口睡眠,以便让其他售票窗口卖票
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				else{
					System.out.println(Thread.currentThread().getName() + "余票不足,停止售票!");
					break;
				}
			}
		}
	}
}

输出:

TickWindow-1准备出票,剩余票数:10张
TickWindow-1卖出一张,剩余票数:9张
TickWindow-1准备出票,剩余票数:9张
TickWindow-1卖出一张,剩余票数:8张
TickWindow-1准备出票,剩余票数:8张
TickWindow-1卖出一张,剩余票数:7张
TickWindow-1准备出票,剩余票数:7张
TickWindow-1卖出一张,剩余票数:6张
TickWindow-1准备出票,剩余票数:6张
TickWindow-1卖出一张,剩余票数:5张
TickWindow-1准备出票,剩余票数:5张
TickWindow-1卖出一张,剩余票数:4张
TickWindow-1准备出票,剩余票数:4张
TickWindow-1卖出一张,剩余票数:3张
TickWindow-1准备出票,剩余票数:3张
TickWindow-1卖出一张,剩余票数:2张
TickWindow-3准备出票,剩余票数:2张
TickWindow-3卖出一张,剩余票数:1张
TickWindow-3准备出票,剩余票数:1张
TickWindow-3卖出一张,剩余票数:0张
TickWindow-3余票不足,停止售票!
TickWindow-2余票不足,停止售票!
TickWindow-1余票不足,停止售票!

2.同步方法.

同步方法就是使用 synchronized 关键字修饰某个方法,synchronized 修饰的实例方法(非static方法)的同步监视器是this.

使用同步方法解决共享资源的多线程访问冲突的一般方式是:

        //把修改共享资源的方法使用synchronized进行修饰
	public synchronized void someMethod(){
		//do something...
	}
	//在run()方法中调用该同步方法
	public void run(){
		someMethod();
	}

下面给出使用同步方法实现的模拟火车售票系统:

(1)通过extends Thread实现:注意tickets变量和setllTickets()函数都需要改为static

public class SellTicket {

    public static void main(String[] args) {
        for(int i=1; i<4; i++){
            TicketWindow ticketWindow = new TicketWindow();
            ticketWindow.setName("TickWindow0-" + i);
            ticketWindow.start();
        }
    }
}

class TicketWindow extends Thread{
    private static int tickets = 10;//车票总量

    @Override
    public void run(){
        while(true){
            if(tickets>0){
                sellTicket();
            }
            else{
                System.out.println(Thread.currentThread().getName() + "余票不足,停止售票!");
                break;
            }
        }
    }

    //同步方法,必须为静态方法
    public static synchronized void sellTicket(){
        if(tickets>0){
            System.out.println(Thread.currentThread().getName() + "准备出票,剩余票数:" + tickets + "张");
            tickets--;
            System.out.println(Thread.currentThread().getName() + "卖出一张,剩余票数:" + tickets + "张");
            try {
                //休眠100ms卖票完会报错ERROR: JDWP Unable to get JNI 1.2 environment, jvm->GetEnv() return code = -2JDWP exit error AGENT_ERROR_NO_JNI_ENV(183):  [../../../src/share/back/util.c:820]
                //Thread.sleep(100);
                Thread.sleep(500);//出票成功后让当前售票窗口睡眠,以便让其他售票窗口卖票
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

(2)通过implement Runnable实现:

public class SellTicket {

	public static void main(String[] args) {
		TicketWindow tw = new TicketWindow();
		for(int i=1; i<4; i++){
			Thread t = new Thread(tw,"TickWindow-" + i);
			t.start();
		}
	}
}

class TicketWindow implements Runnable{
	private int tickets = 10;//车票总量
	@Override
	public void run(){
		while(true){
			sellTicket();
		}
	}
	public synchronized void sellTicket(){
			if(tickets>0){
				System.out.println(Thread.currentThread().getName() + "准备出票,剩余票数:" + tickets + "张");                    
	            tickets--;                                                                                              
	            System.out.println(Thread.currentThread().getName() + "卖出一张,剩余票数:" + tickets + "张");
	            try {
					Thread.sleep(500);//出票成功后让当前售票窗口睡眠,以便让其他售票窗口卖票
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			else{
				System.out.println(Thread.currentThread().getName() + "余票不足,停止售票!");
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
	}
}

输出:

TickWindow-1准备出票,剩余票数:10张
TickWindow-1卖出一张,剩余票数:9张
TickWindow-1准备出票,剩余票数:9张
TickWindow-1卖出一张,剩余票数:8张
TickWindow-1准备出票,剩余票数:8张
TickWindow-1卖出一张,剩余票数:7张
TickWindow-1准备出票,剩余票数:7张
TickWindow-1卖出一张,剩余票数:6张
TickWindow-1准备出票,剩余票数:6张
TickWindow-1卖出一张,剩余票数:5张
TickWindow-1准备出票,剩余票数:5张
TickWindow-1卖出一张,剩余票数:4张
TickWindow-1准备出票,剩余票数:4张
TickWindow-1卖出一张,剩余票数:3张
TickWindow-1准备出票,剩余票数:3张
TickWindow-1卖出一张,剩余票数:2张
TickWindow-1准备出票,剩余票数:2张
TickWindow-1卖出一张,剩余票数:1张
TickWindow-1准备出票,剩余票数:1张
TickWindow-1卖出一张,剩余票数:0张
TickWindow-1余票不足,停止售票!
TickWindow-1余票不足,停止售票!
TickWindow-1余票不足,停止售票!
TickWindow-1余票不足,停止售票!
TickWindow-1余票不足,停止售票!
TickWindow-3余票不足,停止售票!
TickWindow-2余票不足,停止售票!
TickWindow-3余票不足,停止售票!
TickWindow-3余票不足,停止售票!

注意:while(true){}要放在run()方法里面,而不是sell方法里. 否则会出现某一个窗口一直把票卖完的情况.

要想让售票窗口在售完票之后停止,需要在run()方法里的作条件限制,修改如下:

public class SellTicket {

	public static void main(String[] args) {
		TicketWindow tw = new TicketWindow();
		for(int i=1; i<4; i++){
			Thread t = new Thread(tw,"TickWindow-" + i);
			t.start();
		}
	}
}

class TicketWindow implements Runnable{
	private int tickets = 10;//车票总量
	@Override
	public void run(){
		while(true){
			if(tickets>0){
				sellTicket();
			}
			else{
				System.out.println(Thread.currentThread().getName() + "余票不足,停止售票!");
				break;
			}
		}
	}
	public synchronized void sellTicket(){
		if(tickets>0){
			System.out.println(Thread.currentThread().getName() + "准备出票,剩余票数:" + tickets + "张");                    
            tickets--;                                                                                              
            System.out.println(Thread.currentThread().getName() + "卖出一张,剩余票数:" + tickets + "张");
            try {
				Thread.sleep(500);//出票成功后让当前售票窗口睡眠,以便让其他售票窗口卖票
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

输出如下:

TickWindow-1准备出票,剩余票数:10张
TickWindow-1卖出一张,剩余票数:9张
TickWindow-1准备出票,剩余票数:9张
TickWindow-1卖出一张,剩余票数:8张
TickWindow-1准备出票,剩余票数:8张
TickWindow-1卖出一张,剩余票数:7张
TickWindow-1准备出票,剩余票数:7张
TickWindow-1卖出一张,剩余票数:6张
TickWindow-1准备出票,剩余票数:6张
TickWindow-1卖出一张,剩余票数:5张
TickWindow-1准备出票,剩余票数:5张
TickWindow-1卖出一张,剩余票数:4张
TickWindow-1准备出票,剩余票数:4张
TickWindow-1卖出一张,剩余票数:3张
TickWindow-1准备出票,剩余票数:3张
TickWindow-1卖出一张,剩余票数:2张
TickWindow-1准备出票,剩余票数:2张
TickWindow-1卖出一张,剩余票数:1张
TickWindow-1准备出票,剩余票数:1张
TickWindow-1卖出一张,剩余票数:0张
TickWindow-1余票不足,停止售票!
TickWindow-3余票不足,停止售票!
TickWindow-2余票不足,停止售票!

注意!

使用 synchronized 修饰run()方法是无效的:

public class SellTicket {

	public static void main(String[] args) {
		TicketWindow tw = new TicketWindow();
		for(int i=1; i<4; i++){
			Thread t = new Thread(tw,"TickWindow-" + i);
			t.start();
		}
	}
}

class TicketWindow implements Runnable{
	private int tickets = 10;//车票总量
	
	@Override
	public synchronized void run(){
		while(true){
			if(tickets>0){
				System.out.println(Thread.currentThread().getName() + "准备出票,剩余票数:" + tickets + "张");                    
	            tickets--;                                                                                              
	            System.out.println(Thread.currentThread().getName() + "卖出一张,剩余票数:" + tickets + "张");
	            try {
					Thread.sleep(500);//出票成功后让当前售票窗口睡眠,以便让其他售票窗口卖票
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			else{
				System.out.println(Thread.currentThread().getName() + "余票不足,停止售票!");
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

会输出:

TickWindow-1准备出票,剩余票数:10张
TickWindow-1卖出一张,剩余票数:9张
TickWindow-1准备出票,剩余票数:9张
TickWindow-1卖出一张,剩余票数:8张
TickWindow-1准备出票,剩余票数:8张
TickWindow-1卖出一张,剩余票数:7张
TickWindow-1准备出票,剩余票数:7张
TickWindow-1卖出一张,剩余票数:6张
TickWindow-1准备出票,剩余票数:6张
TickWindow-1卖出一张,剩余票数:5张
TickWindow-1准备出票,剩余票数:5张
TickWindow-1卖出一张,剩余票数:4张
TickWindow-1准备出票,剩余票数:4张
TickWindow-1卖出一张,剩余票数:3张
TickWindow-1准备出票,剩余票数:3张
TickWindow-1卖出一张,剩余票数:2张
TickWindow-1准备出票,剩余票数:2张
TickWindow-1卖出一张,剩余票数:1张
TickWindow-1准备出票,剩余票数:1张
TickWindow-1卖出一张,剩余票数:0张
TickWindow-1余票不足,停止售票!
TickWindow-1余票不足,停止售票!
TickWindow-1余票不足,停止售票!
TickWindow-1余票不足,停止售票!

原因见:

java - Should you synchronize the run method? Why or why not? - Stack Overflow

参考:

java多线程之火车售票系统模拟_本案例模拟一个火车售票系统,假设仅剩3张火车票,5个窗口同时进行售票。如果票数小-CSDN博客

  • 18
    点赞
  • 97
    收藏
    觉得还不错? 一键收藏
  • 10
    评论
Java多线程模拟售票程序可以通过实现Runnable接口或继承Thread类来实现。这两种方式都可以达到多线程的效果。在实现Runnable接口的情况下,可以创建一个实现了Runnable接口的类,并在该类中重写run()方法。然后,通过创建多个线程对象,并将该实现类的对象作为参数传入Thread的构造函数中,然后调用start()方法启动线程。在实现Thread类的情况下,可以直接创建继承了Thread类的子类,并在子类中重写run()方法。然后,通过创建多个子类对象,调用start()方法启动线程。 下面是一个使用实现Runnable接口的例子: ``` public class TicketSalesByRunnable { public static void main(String[] args) { SellTicket02 sellTicket02 = new SellTicket02(); new Thread(sellTicket02).start(); new Thread(sellTicket02).start(); new Thread(sellTicket02).start(); } } class SellTicket02 implements Runnable { private int ticketNum = 100; @Override public void run() { while (true) { if (ticketNum <= 0) { System.out.println("没有余票!"); break; } try { Thread.sleep(50); } catch (InterruptedException e) { throw new RuntimeException(e); } System.out.println("窗口" + Thread.currentThread().getName() + "售出一张票。" + "剩余票数:" + (--ticketNum)); } } } ``` 下面是一个使用继承Thread类的例子: ``` public class TicketSalesByThread { public static void main(String[] args) { SellTicket sellTicket = new SellTicket(); SellTicket sellTicket1 = new SellTicket(); SellTicket sellTicket2 = new SellTicket(); sellTicket.start(); sellTicket1.start(); sellTicket2.start(); } } class SellTicket extends Thread { private static int ticketNum = 100; @Override public void run() { while (true) { if (ticketNum <= 0) { System.out.println("没有余票!"); break; } try { Thread.sleep(50); } catch (InterruptedException e) { throw new RuntimeException(e); } System.out.println("窗口" + Thread.currentThread().getName() + "售出一张票。" + "剩余票数:" + (--ticketNum)); } } } ```
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值