java中多線程安全性和同步的常用方法

1、多線程安全性問題,即多線程在什麼場景下會出現異常?

多個線程同時調用一個共享的變量(對象),比如當某個線程操作車票的過程中,尚未操作完成時,其他線程參與進來,也操作車票。

 

2、在Java中,我們通過同步機制,來解決線程的安全問題。

3、有幾種同步機制?

有3種,同步代碼塊、同步方法、Lock;

 

4、同步代碼塊

 代碼如下:

synchronized(同步監視器){
     //需要被同步的代碼
 }

注意:

(1)同步監視器,俗稱:鎖。任何一個類的對象,都可以充當鎖。要求:多個線程必須要共用同一把鎖。同步監視器必須唯一,且是一個對象。也就是多個線程共享一個同步監視器對象。否則同步代碼塊不生效。

 (2)包裹的代碼是操作共享數據的代碼,即爲需要被同步的代碼。不能多,也不能少,否則就會出錯。

(3)共享數據:多個線程共同操作的變量。

 (4)在實現Runnable接口創建多線程的方式中,我們可以考慮使用this充當同步監視器。

(5)在繼承Thread類創建多線程的方式中,慎用this充當同步監視器,考慮使用當前類充當同步監視器。也就是"類名.class",比如“Student.class”。

實例代碼1(實現Runnable接口):

class Window1 implements Runnable{

    private int ticket = 100;
//    Object obj = new Object();
//    Dog dog = new Dog();
    @Override
    public void run() {
//        Object obj = new Object();
        while(true){
            synchronized (this){//此時的this:唯一的Window1的對象   //方式二:synchronized (dog) {

                if (ticket > 0) {

                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    System.out.println(Thread.currentThread().getName() + ":賣票,票號爲:" + ticket);


                    ticket--;
                } else {
                    break;
                }
            }
        }
    }
}
View Code

實例代碼2(繼承Thread):

class Window2 extends Thread{


    private static int ticket = 100;

    private static Object obj = new Object();

    @Override
    public void run() {

        while(true){
            //正確的
//            synchronized (obj){
            synchronized (Window2.class){//Class clazz = Window2.class,Window2.class只會加載一次
                //錯誤的方式:this代表着t1,t2,t3三個對象
//              synchronized (this){

                if(ticket > 0){

                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    System.out.println(getName() + ":賣票,票號爲:" + ticket);
                    ticket--;
                }else{
                    break;
                }
            }

        }

    }
}
View Code

 

5、同步方法

(1)同步方法仍然涉及到同步監視器,只是不需要我們顯式的聲明。

(2)非靜態的同步方法,同步監視器是:this
  靜態的同步方法,同步監視器是:當前類本身

實例代碼1(實現Runnable接口)

class Window3 implements Runnable {

    private int ticket = 100;

    @Override
    public void run() {
        while (true) {

            show();
        }
    }

    private synchronized void show(){//同步監視器:this
        //synchronized (this){

            if (ticket > 0) {

                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println(Thread.currentThread().getName() + ":賣票,票號爲:" + ticket);

                ticket--;
            }
        //}
    }
}
View Code

 

實例代碼2(繼承Thread)

class Window4 extends Thread {


    private static int ticket = 100;

    @Override
    public void run() {

        while (true) {

            show();
        }

    }
    private static synchronized void show(){//同步監視器:Window4.class
        //private synchronized void show(){ //同步監視器:t1,t2,t3。此種解決方式是錯誤的
        if (ticket > 0) {

            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println(Thread.currentThread().getName() + ":賣票,票號爲:" + ticket);
            ticket--;
        }
    }
}
View Code

 

 

 

6、單例模式中懶漢模式的線程安全的代碼:

lass Bank{

    private Bank(){}

    private static Bank instance = null;

    public static Bank getInstance(){
        //方式一:效率稍差
//        synchronized (Bank.class) {
//            if(instance == null){
//
//                instance = new Bank();
//            }
//            return instance;
//        }
        //方式二:效率更高
        if(instance == null){

            synchronized (Bank.class) {
                if(instance == null){

                    instance = new Bank();
                }

            }
        }
        return instance;
    }

}
View Code

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章