1. 程式人生 > 其它 >同步鎖 synchronized

同步鎖 synchronized

synchronized方法和synchronized塊

同步方法: public synchronized void method(int args){}
synchronized方法控制對“物件”的訪問﹐每個物件對應一把鎖﹐每個synchronized方法都必須獲得呼叫該方法的物件的鎖才能執行﹐否則執行緒會阻塞,方法一旦執行﹐就獨佔該鎖,直到該方法返回才釋放鎖﹐後面被阻塞的執行緒才能獲得這個鎖,繼續執行
缺陷:若將一個大的方法申明為synchronized將會影響效率

synchronized 修飾詞

package Thread.Demo09;

/** synchronized 修飾詞
 * 只能1個執行緒對物件操作
 * @author liu
 */
public class UnSafeBuyTick {
    public static void main(String[] args) {
        BuyTick buyTick = new BuyTick();
        Thread thread1 = new Thread(buyTick,"A");
        Thread thread2 = new Thread(buyTick,"B");
        Thread thread3 = new Thread(buyTick,"C");
        thread1.start();
        thread2.start();
        thread3.start();
    }
}


class BuyTick implements Runnable {
    private int tick = 10;
    boolean flag = true;//外部停止方式

    @Override
    public void run() {
        while(flag){
            buy();
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private synchronized void  buy() {
        if (tick <= 0) {
            flag=false;
            return ;
        }
        System.out.println(Thread.currentThread().getName() + "買到" + tick--);
    }
}

synchronized(){} 同步鎖方法塊

package Thread.Demo09;

import java.util.ArrayList;
import java.util.List;

/**synchronized(){} 同步鎖方法塊
 * @author liu
 */
public class UnSafeThread02 {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        for (int i = 0; i < 10000; i++) {
            new Thread(() -> {
              synchronized (list){ list.add(Thread.currentThread().getName());
            }}).start();
        }
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(list.size());
    }
}