首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件开发 >

JAVA多线程设计方式二 Immutable Pattern

2012-07-24 
JAVA多线程设计模式二 Immutable PatternString? 与? StringBuffer 可以互相转换。一个是线程安全的,一个是

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();    }}

?

类中字段不会被修改。所以是安全的。

热点排行