Compile a train station ticket selling program -- ticket tickets are sold at the same time in three windows

Source: Internet
Author: User

[Html] <span style = "color: # 3366ff;">/* implement the Runnable interface to create a Thread class to share a data </span> [html] <span style = "color: # 3366ff; "> compile a train station ticketing program -- sell tickets in three windows at the same time </span> <span style =" color: # 3366ff; "> */class PP implements Runnable {// class PP public int tickets = 100 that implements a Runnable interface; // a total of 100 tickets String str = new String ("123"); // create a String object to pass the local name to the public void run () {while (true) parameter) {// when the condition is true synchronized (this. str) {// (the synchronization parameter must be the name of an object) // when the tt thread determines that the condition is true, lock str and execute internal code, when the internal code is not fully executed, the CPU may be snatched by other threads, but when it is determined that there is a lock in synchronization, it will be waiting outside and cannot enter, ensure that only one thread is executed internally. After tt executes the internal code and exits, it will seize the CPU execution right on the same starting line as tt1. if (tickets> 0) {System. out. println (Thread. currentThread (). getName () + "sold tickets:" + tickets); tickets --;} else {break ;}}}}} public class Threade_14 {public static void main (String [] args) {PP pp = new PP (); Thread tt1 = new Thread (pp ); // construct the Thread object to implement the Runnable class PP Thread tt2 = new Thread (pp); Thread tt3 = new Thread (pp); tt1.start (); // enable the Thread tt2.start (); tt3.start () ;}</span>

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.