Java多線程實現簡單的售票程式

來源:互聯網
上載者:User

標籤:util   賣出   oid   線程   多線程程式   售票   name   current   設計   

設計一個多線程程式如下:設計一個火車售票類比程式。假如火車站要有100張火車票要賣出,現在有5個售票點同時售票,用5個線程類比這5個售票點的售票情況

1、要求列印出每個售票點所賣出的票號

2、各售票點不能售出相同票號的火車票

 

 

package com.hebust.java.third;

 

import java.util.Random;

 

public class SaleTicket implements Runnable {

 

public int total;

public int count;

 

public SaleTicket() {

total = 100;

count = 0;

}

 

public void run() {

while (total > 0) {

synchronized (this) {

if(total > 0) {

try {

//Thread.sleep(800);

Thread.sleep(new Random().nextInt(1000));

} catch (InterruptedException e) {

e.printStackTrace();

}

count++;

total--;

 

System.out.println(Thread.currentThread().getName() + "\t當前票號:" + count);

}

}

}

 

}

 

public static void main(String[] args) {

SaleTicket st = new SaleTicket();

for(int i=1; i<=5; i++) {

new Thread(st, "售票點" + i).start();

}

}

}

Java多線程實現簡單的售票程式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.