Java多線程基礎(四)——Immutable模式

1、定義

Immutable是「永恆的」「不會改變」的意思。在Immutable Patttern中,有着可以保證明例狀態毫不會改變的類(immutable 類)。由於訪問這個實例時,能夠省去使用共享互斥機制所會浪費的時間,提升系統性能。java.lang.String就是一個Immutable的類。java

2、模式案例

案例:
Person類,具備姓名(name)、地址(address)等字段。字段都是私有的,只能經過構造器來設置,且只有get方法,沒有set方法。這時,即便有多個線程同時訪問相同實例,Person類也是安全的,它的全部方法都不須要定義成synchronized。安全

Person定義:性能

public final class Person {
    private final String name;
    private final String address;
    public Person(String name, String address) {
        this.name = name;
        this.address = address;
    }
    public String getName() {
        return name;
    }
    public String getAddress() {
        return address;
    }
    public String toString() {
        return "[ Person: name = " + name + ", address = " + address + " ]";
    }
}

線程定義:this

public class PrintPersonThread extends Thread {
    private Person person;
    public PrintPersonThread(Person person) {
        this.person = person;
    }
    public void run() {
        while (true) {
            System.out.println(Thread.currentThread().getName() + " prints " + person);
        }
    }
}

執行:spa

public class Main {
    public static void main(String[] args) {
        Person alice = new Person("Alice", "Alaska");
        new PrintPersonThread(alice).start();
        new PrintPersonThread(alice).start();
        new PrintPersonThread(alice).start();
    }
}

3、模式講解

Immutable模式的角色以下:線程

  • Immutable(不變的)參與者

Immutable參與者是一個字段值沒法更改的類,也沒有任何用來更改字段值的方法。當Immutable參與者的實例創建後,狀態就徹底再也不變化。code

適用場景:
Immutable模式的優勢在於,「不須要使用synchronized保護」。而「不須要使用synchronized保護」的最大優勢就是可在不喪失安全性與生命性的前提下,提升程序的執行性能。若實例由多數線程所共享,且訪問很是頻繁,Immutable模式就能發揮極大的優勢。rem

相關文章
相關標籤/搜索