[JavaSE] multithreading (ticket sales example), javase ticket sales

Source: Internet
Author: User

[JavaSE] multithreading (ticket sales example), javase ticket sales

Requirement: simple ticket buying program, ticket selling in multiple windows, multi-thread

 

Define a class Ticket to implement the Runnable interface,

Defines the number of digits of the int type in the member attribute nums.

Implement the run () method, in the run Method

While (true) infinite loop, print nums --

 

Get Ticket object, new

Get the Thread () object, new, and construct the parameter: Runable object

Call the start () method of the Thread object to enable the Thread.

 

In this case, thread security issues occur. Use the synchronized synchronization code block to solve security problems.

 

Avoid deadlock. nested synchronization in synchronization, but different locks

class Ticket implements Runnable {    private int nums = 100;    @Override    public void run() {        while (true) {            synchronized (this) {                if (nums > 0) {                    try {                        Thread.sleep(10);                    } catch (Exception e) {                        e.printStackTrace();                    }                    System.out.println(Thread.currentThread().getName() + "==="                            + (nums--));                }else{                    break;                }            }        }    }}public class TicketDemo {    /**     * @param args     */    public static void main(String[] args) {        Ticket ticket = new Ticket();        new Thread(ticket).start();        new Thread(ticket).start();        new Thread(ticket).start();        new Thread(ticket).start();    }}

 

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.