example, suppose to be a ticket-selling system, where multiple threads (2 threads in an example) manipulate the same variable Ticketcount (number of remaining votes).
Expected: Multiple threads synchronize to the same variable without causing confusion.
public class Test implements Runnable {
Private String ThreadName;
private int ticketcount;
Public Test (String threadname, int ticketcount) {
This.threadname = ThreadName;
This.ticketcount = Ticketcount;
}
public synchronized int Sellticket () {
return ticketcount--;
}
@Override
public void Run () {
TODO auto-generated Method Stub
while (Ticketcount > 0) {
System.out.println (Getthreadname () + ":" + sellticket ());
}
}
Public String Getthreadname () {
Thread a = Thread.CurrentThread ();
return A.getname ();
}
public static void Main (string[] args) {
Test T1 = new Test ("Ticket available", 10);
Thread thread1 = new Thread (t1,
"1 window Sell ticket, ticket available");
Thread thread2 = new Thread (t1,
"2 window Sell ticket, ticket available");
Thread1.start ();
Thread2.start ();
}
}
----------------------Print results (different every time)----------------------
2 window Sell ticket, ticket Available:9
2 window Sell ticket, ticket Available:8
2 window Sell ticket, ticket Available:7
2 window Sell ticket, ticket available:6
2 window Sell ticket, ticket Available:5
2 window Sell ticket, ticket Available:4
1 window Sell ticket, ticket available:10
2 window Sell ticket, ticket Available:3
1 window Sell ticket, ticket available:2
2 window Sell ticket, ticket available:1