Multi-threaded Sell ticket code

Source: Internet
Author: User
Tags ticket

package Com.loaderman.syn; public class Demo_ticket {/** * demand: railway ticketing, altogether 100, through four    The window is sold out.      */public static void main (string[] args) {new Ticket (). Start ();      New Ticket (). Start ();      New Ticket (). Start ();   New Ticket (). Start ();   }} class Ticket extends Thread {private static int Ticket = 100;    private static Object obj = new Object (); If you use a reference data type member variable as a lock object, you must be static public void run () {while (true) {synchronized (Ticket.class) {if (Ti            Cket <= 0) {break;           } try {Thread.Sleep (10);            Thread 1 sleeps, thread 2 sleeps, thread 3 sleeps, thread 4 sleeps} catch (Interruptedexception e) {e.printstacktrace (); } System.out.println (GetName () + "...         This is the first "+ ticket--+" ticket "); }      }   }}
Package Com.loaderman.syn; public class Demo_ticket {/** * @param args * railway station example of selling tickets with implementation runnable interface */public static void Main (string[] Arg      s) {Myticket MT = new Myticket ();      New Thread (MT). Start ();      New Thread (MT). Start ();      New Thread (MT). Start ();            New Thread (MT). Start ();           /*thread T1 = new Thread (MT);      Starting a thread multiple times is illegal t1.start ();      T1.start ();      T1.start ();   T1.start (); */}} class Myticket implements Runnable {private int tickets = 100;                @Override public void Run () {while (true) {synchronized (this) {if (tickets <= 0) {            Break           } try {Thread.Sleep (10);            Thread 1 sleeps, thread 2 sleeps, thread 3 sleeps, thread 4 sleeps} catch (Interruptedexception e) {e.printstacktrace (); } System.out.println (Thread.CurrentThread (). GetName () + "...         This is the first "+ tickets--+" ticket "); }      }   }}

Multi-threaded ticket sales Code

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.