Java Multithreading Security

Source: Internet
Author: User
Tags ticket

Package Swingexample;public class Multithreadsafe implements runnable{private int nticketcount = 10;//remaining train ticket number private STR  ing strpurchasername;//ticket person name public static void main (string[] args) {//TODO auto-generated method Stubmultithreadsafe t = New Multithreadsafe ("man"); T.buytickets ();} public void Buytickets () {//assumes a maximum of 5 persons to purchase tickets at the same time multithreadsafe man1 = new Multithreadsafe ("Man1"); Multithreadsafe man2 = new Multithreadsafe ("man2"); Multithreadsafe man3 = new Multithreadsafe ("Man3"); Multithreadsafe man4 = new Multithreadsafe ("Man4"); Multithreadsafe man5 = new Multithreadsafe ("Man5"); thread T1 = new Thread (MAN1); Thread t2 = new Thread (MAN2); thread t3 = new Thread (MAN3); thread T4 = new Thread (MAN4); Thread T5 = new Thread (MAN5); T1.start (); T2.start (); T3.start (); T4.start (); T5.start ();} Public Multithreadsafe (String strpurchasername) {//TODO auto-generated Constructor stubthis.strpurchasername = Strpurchasername;} @Overridepublic void Run () {//TODO auto-generated method Stubwhile (Nticketcount; 0) {synchronized ("") {//Multithreading sync nticketcount--;if (Nticketcount = = 0) {System.out.println (This.strpurchasername +) come to purchase tickets, But the tickets are sold out! ");} else if (Nticketcount > 0) {System.out.println (This.strpurchasername + "come to purchase ticket, current remaining ticket:" + Nticketcount);} else {System.out.println ("Excess ticket management system exception, please contact the system administrator.") ");}} try {thread.sleep;} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}

Java Multithreading Security

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.