代碼分享:模擬售票 學(xué)習(xí)多線程
作者:楊軍軍
一段簡單的火車票Java編程代碼,主要是加強(qiáng)多線程的學(xué)習(xí)。
【代碼說明】
假設(shè)有火車票100張,創(chuàng)建10個(gè)線程模擬10個(gè)售票點(diǎn),每個(gè)售票點(diǎn)100毫秒賣一張票。 打印出售票過程,注意使用synchronized確保同一張票只能賣出一次。輸出格式如下:
第4售票點(diǎn)賣出第100張票
第2售票點(diǎn)賣出第101張票 ……
【代碼片段】
- class T4E02
- {
- public static void main(String[] args)
- {
- Resource rs = new Resource(100);
- for (int i=0;i<10 ;i++ )
- {
- new Thread(new Seller(i,rs)).start();
- }
- }
- }
- /**
- * 資源類
- * 定義了票的總數(shù),和同步了的售票方法
- */
- class Resource
- {
- int ticketNum = 50;
- boolean flag = false ; // 定義票是否賣完
- public Resource(){}
- public Resource(int num)
- {
- this.ticketNum = num;
- }
- public synchronized void sellTicket(Seller s)
- {
- if (ticketNum > 0)
- {
- System.out.println("第" + s.num + "售票點(diǎn)賣出了第" + ticketNum + "張票……");
- ticketNum--;
- }
- else
- {
- flag = true;
- }
- }
- }
- /**
- * 售票點(diǎn)類
- *
- */
- class Seller implements Runnable
- {
- int num;
- Resource rs;
- public Seller(int num,Resource rs)
- {
- this.num = num;
- this.rs = rs;
- }
- public final void run()
- {
- while (!rs.flag)
- {
- /**
- * 調(diào)用資源類的同步方法
- */
- rs.sellTicket(this);
- try
- {
- Thread.sleep(100);
- }
- catch (InterruptedException e)
- {
- e.printStackTrace();
- }
- }
- }
- }
【圖片效果】
原文鏈接:http://www.oschina.net/code/snippet_85011_6481
【編輯推薦】
責(zé)任編輯:林師授
來源:
開源中國社區(qū)