Java multithreaded implementation of simple ticketing procedures

Source: Internet
Author: User

Design a multi-threaded program as follows: Design a train ticketing simulator. If there are 100 train tickets to sell at the station, there are now 5 tickets available at the same time, with 5 threads to simulate the sale of the 5 ticket booths.

1. Required to print out the ticket sold at each ticket point

2. Tickets for the same ticket cannot be sold at each ticketing point

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 Current ticket:" + count);

}

}

}

}

public static void Main (string[] args) {

Saleticket st = new Saleticket ();

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

New Thread (St, "ticket point" + i). Start ();

}

}

}

Java multithreaded implementation of simple ticketing procedures

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.