Define a class to implement the Runnable interface, define a ticketing method that needs to be synchronized, and then override the sale method of the Run method call ticket
[Java]View PlainCopy
- Class Saleticket implements runnable{
- private int tickets = 100;
- private synchronized void sale () {
- if (Tickets > 0) {
- System.out.println (Thread.CurrentThread (). GetName () + "sell first" + (tickets--) +"Ticket");
- try{
- Thread.Sleep (100);
- }catch (Interruptedexception e) {
- E.printstacktrace ();
- }
- }
- }
- public Void Run () {
- While (Tickets > 0) {
- Sale ();
- }
- }
- }
- Public class Javatest {
- public static void Main (string[] args) {
- Saleticket st = New Saleticket ();
- Thread T1 = new Thread (St, "one Window");
- Thread t2 = new Thread (St, "window number second");
- thread t3 = new Thread (St, "window number third");
- thread t4 = new Thread (St,"window number fourth");
- T1.start ();
- T2.start ();
- T3.start ();
- T4.start ();
- }
- }
Java multi-threaded ticketing problem