当前位置:网站首页>Two methods of thread synchronization

Two methods of thread synchronization

2022-07-07 05:14:00 Yang Asang 815

1: Synchronization code block

 public void UpdateMoney(Double price){
        System.out.println(Thread.currentThread() + " Came in ");
        synchronized (this){
            if(price<=money){
                // Withdraw money 
                System.out.println(Thread.currentThread()+" To withdraw money "+price);
                money-=price;
                System.out.println(" The remaining balance "+money);
            }else {
                System.out.println(Thread.currentThread()+" I'm sorry ! Lack of balance ");
            }
        }
    }
 synchronized ( Synchronization lock object ){ 
 Code for operating shared resources  
} 
   

Be careful. : The synchronization lock object should be unique , When using instance methods , It is recommended to use shared resources , such as this,

When using static methods , Bytecode is recommended , such as : Class name .class

Method 2: Synchronization method

/***
     *  The way to get money 
     * @param price  Amount to be withdrawn 
     */
    public synchronized void UpdateMoney(Double price){
        System.out.println(Thread.currentThread() + " Came in ");
        Lock lock=new ReentrantLock();
        lock.lock();
            if(price<=money){
                // Withdraw money 
                System.out.println(Thread.currentThread()+" To withdraw money "+price);
                money-=price;
                System.out.println(" The remaining balance "+money);
            }else {
                System.out.println(Thread.currentThread()+" I'm sorry ! Lack of balance ");
            }
        lock.unlock();
    }

Modifier Back add synchronized, And then call Lock Interface ReentrantLock Implementation class ,

Use lock() Method lock ,unlock() Method release lock ,

原网站

版权声明
本文为[Yang Asang 815]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207062309112406.html