Create first RunnableImp class :
package demo08 Thread safe static synchronization method ; // Case of realizing ticket purchase // There is a thread safety problem in ticket selling : Sold non-existent tickets and duplicate tickets
// A scheme of using thread safety : Use synchronization method /* Use steps : 1. Extract the code blocks of the accessed shared data , Put it in a method
2. Add a to the method synchornized Modifier format : Define method format Modifier synchornized Return type Method name ( parameter list ){
Thread safe code with possible problems } */ public class RunnableImp implements Runnable { // Define a ticket source shared by multiple threads
private static int ticket=100; // Create a lock object Object obj=new Object(); // Define thread tasks : Buy a ticket
@Override public void run() { // Use the dead loop to repeat the ticket selling while(true){ payTicketStatic(); }
} /* Define a static synchronization method : Synchronous methods also lock the code inside the method , Let only one method execute Lock object is not this
this It is generated after the object is created , Static methods are better than objects , The lock object of static method is of this class class attribute --class File object */ public static
/*synchronized*/ void payTicketStatic(){ // Judge whether the ticket exists
synchronized(RunnableImp.class){ if(ticket>0){ // In order to improve the number of safety problems . Let the program sleep try {
Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); }
System.out.println(Thread.currentThread().getName()+"--- Selling tickets "+ticket+" Ticket ");
ticket--; } } } }
Recreate Ticket class :
package demo08 Thread safe static synchronization method ; // Simulated ticket buying case , Sell shared tickets public class Ticket { public
static void main(String[] args) { // Create the implementation class object of the interface RunnableImp run =new
RunnableImp(); // establish Thread Class object , Transfer in construction method Runnable Interface object Thread t0=new Thread(run);
Thread t1=new Thread(run); Thread t2=new Thread(run); // Open thread t0.start();
t1.start(); t2.start(); } }
result :
Technology
Daily Recommendation