multithreaded analog network in Java grab ticket code

Source: Internet
Author: User
Tags ticket

First, the type of ticket robbery:

Package Cn.jbit.ticket;public class Ticket implements Runnable {private int num = 0;//number of votes private int count = 10;//number of votes left Boolean flag = false; @Overridepublic void Run () {while (true) {//when there is no residual ticket, jump out of the loop if (count <= 0) {break;} Num++;count--;try {thread.sleep (500);//analog Network delay} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} System.out.println ("Show ticketing Information:" + thread.currentthread (). GetName () + "grab the first" + num + "ticket, remaining" + Count + "Ticket");}} }

  

Second, the test class:

Package Cn.jbit.ticket;public class Test {/** * @param args */public static void main (string[] args) {ticket ticket=new Ti Cket ();//Instantiate several Rob users thread mary = new Thread (ticket, "Mary"); Thread jack = new Thread (ticket, "Jack"); Mary.start (); Jack.start ();}}

Code that does not use thread synchronization results in the following: multiple people will grab the same ticket .

With thread synchronization, the code looks like this:

Package Cn.jbit.ticket;public class Ticket implements Runnable {private int num = 0;//number of votes private int count = 10;//number of votes left Boolean flag = false; @Overridepublic void Run () {while (true) {synchronized (this) {////without a residual ticket, jump out of the loop if (count <= 0) {break ;} Num++;count--;try {thread.sleep (500);//analog Network delay} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} System.out.println ("Show ticket info:" + thread.currentthread (). GetName () + "grab the first" + num + "ticket, remaining" + Count + "Ticket");}} }

The effect is as follows:

multithreaded analog network in Java grab ticket 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.