Java(38)解決多線程數據安全問題


作者:季沐測試筆記
原文地址https://www.cnblogs.com/testero/p/15135598.html
博客主頁https://www.cnblogs.com/testero

1 同步代碼塊

1.1 基本語句

synchronized (任意對象) {
操作共享代碼
}

代碼示例


public class SellTicket implements Runnable {
    private int tickets = 100;
    private Object object = new Object();


    @Override
    public void run() {
        while (true) {
            synchronized (object) {
                if (tickets > 0) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "正在出售第" + tickets + "張票");
                    tickets--;
                }
            }
        }
    }


    public static void main(String[] args) {

        SellTicket sellTicket = new SellTicket();

        Thread thread1 = new Thread(sellTicket, "窗口1");
        Thread thread2 = new Thread(sellTicket, "窗口2");
        Thread thread3 = new Thread(sellTicket, "窗口3");
        thread1.start();
        thread2.start();
        thread3.start();
    }
}

1.2優缺點:

  • 解決了多線程的數據安全問題
  • 多線程時,每個線程都會判斷同步上的鎖,耗費資源,降低了程序的運行效率

2 同步方法

2.1 同步方法:將synchronized關鍵字加到方法上

  • 格式: 修飾符 synchronized 返回值類型 方法名(){ }
  • 同步方法的鎖對象是this

2.2 同步靜態方法,就是把synchronized關鍵字加到靜態方法上

  • 格式: 修飾符 static synchronized 返回值類型 方法名(){ }
  • 同步靜態方法的鎖對象是 類名.class

代碼示例

public class SellTicket implements Runnable {
//    private int tickets = 100;
    private static int tickets = 100;
    private Object object = new Object();
    private int x = 0;


    @Override
    public void run() {
        while (true) {
            if (x % 2 == 0) {
//                synchronized (object) {
//                synchronized (this) {
                synchronized (SellTicket.class) {
                    if (tickets > 0) {
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println(Thread.currentThread().getName() + "正在出售第" + tickets + "張票");
                        tickets--;
                    }
                }
            } else {
//                synchronized (object) {
//                    if (tickets > 0) {
//                        try {
//                            Thread.sleep(100);
//                        } catch (InterruptedException e) {
//                            e.printStackTrace();
//                        }
//                        System.out.println(Thread.currentThread().getName() + "正在出售第" + tickets + "張票");
//                        tickets--;
//                    }
//                }
                sellTicket();
            }
            x++;
        }
    }

//    private void sellTicket(){
//        synchronized (object) {
//            if (tickets > 0) {
//                try {
//                    Thread.sleep(100);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//                System.out.println(Thread.currentThread().getName() + "正在出售第" + tickets + "張票");
//                tickets--;
//            }
//        }
//    }

//    private synchronized void sellTicket(){
//            if (tickets > 0) {
//                try {
//                    Thread.sleep(100);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//                System.out.println(Thread.currentThread().getName() + "正在出售第" + tickets + "張票");
//                tickets--;
//            }
    private static synchronized void sellTicket(){
        if (tickets > 0) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "正在出售第" + tickets + "張票");
            tickets--;
        }

    }



    public static void main(String[] args) {

        SellTicket sellTicket = new SellTicket();

        Thread thread1 = new Thread(sellTicket, "窗口1");
        Thread thread2 = new Thread(sellTicket, "窗口2");
        Thread thread3 = new Thread(sellTicket, "窗口3");
        thread1.start();
        thread2.start();
        thread3.start();
    }
}

3 lock鎖

3.1 lock實現提供比使用synchronized方法和語句可獲得更廣泛的操作

  • 加鎖解鎖方法

    方法名 說明
    void lock() 獲得鎖
    void unlock() 釋放鎖

3.2 lock是接口不能直接實例化,采用實現類實例化ReentrantLock

  • ReentrantLock構造方法

    方法名 說明
    ReentrantLock() 創建一個ReentrantLock的實例
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;



public class SellTicket implements Runnable {
    private int tickets = 100;
    private Object object = new Object();
    private Lock lock = new ReentrantLock();


    @Override
    public void run() {
        while (true) {
            try {
                lock.lock();
                if (tickets > 0) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "正在出售第" + tickets + "張票");
                    tickets--;
                }
            } finally {
                lock.unlock();

            }
        }

    }

    public static void main(String[] args) {

        SellTicket sellTicket = new SellTicket();

        Thread thread1 = new Thread(sellTicket, "窗口1");
        Thread thread2 = new Thread(sellTicket, "窗口2");
        Thread thread3 = new Thread(sellTicket, "窗口3");
        thread1.start();
        thread2.start();
        thread3.start();
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM