JAVA多线程设计模式二 Immutable Pattern
String? 与? StringBuffer 可以互相转换。
一个是线程安全的,一个是非线程安全的。
?
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 + " ]"; }}
?
?
?
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); } }}
?
?
?
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(); }}
?
类中字段不会被修改。所以是安全的。