Simulated ticket window, with 4 threads to simulate 4 windows in the ticket, a total of 8 tickets, with thread synchronization to achieve

Source: Internet
Author: User
Tags ticket

Simulated ticket window, with 4 threads to simulate 4 windows in the ticket, a total of 8 tickets, with thread synchronization to achieve
public class Ticket {

public static void Main (string[] args) {
for (int i=0;i<4;i++) {
New Sellwindow (). Start ();
}
}
}

Class Sellwindow extends Thread {
private static int ticketall = 100;
private static Object obj = new Object ();

public void Run () {
while (true) {
Synchronized (obj) {
if (Ticketall > 0) {
/* Try {
Thread.Sleep (10);
}
catch (Exception ex) {
}*/

ticketall--;
System.out.println (GetName () + "ticketing" + Ticketall);
System.out.println (GetName () + "sell" + "Tickets_" + (100-ticketall));
} else {
Break
}
}
}
}

}

Simulated ticket window, with 4 threads to simulate 4 windows in the ticket, a total of 8 tickets, with thread synchronization to achieve

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.