[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(); }}