public class ChocolateFactory {
private boolean empty;
private boolean boiled;
public volatile static ChocolateFactory uniqueInstance = null;
private ChocolateFactory() {
empty = true;
boiled = false;
}
public static ChocolateFactory getInstance() {
if (uniqueInstance == null) {
synchronized (ChocolateFactory.class) {
if (uniqueInstance == null) {
uniqueInstance = new ChocolateFactory();
}
}
}
return uniqueInstance;
}
public void fill() {
if (empty) {
// 娣诲姞鍘熸枡宸у厠鍔涘姩浣�
empty = false;
boiled = false;
}
}
public void drain() {
if ((!empty) && boiled) {
// 鎺掑嚭宸у厠鍔涘姩浣�
empty = true;
}
}
public void boil() {
if ((!empty) && (!boiled)) {
// 鐓哺
boiled = true;
}
}
}
volatile关键词,可以百度详细了解
下面这个函数是对经典的单例模式的优化
public static ChocolateFactory getInstance() {
if (uniqueInstance == null) {
synchronized (ChocolateFactory.class) {
if (uniqueInstance == null) {
uniqueInstance = new ChocolateFactory();
}
}
}
return uniqueInstance;
}
写博客的热情日益消减
下面是对synchronized的讲解:
上面的代码线程锁实际上是对类的锁:用法:
可以先看看给静态方法加锁:
Synchronized修饰静态方法,用法如下:
public synchronized static void method() {
}
静态方法是属于类的而不属于对象的。synchronized修饰的静态方法锁定的是这个类的所有对象。
class SyncThread implements Runnable {
private static int count;
public SyncThread() {
count = 0;
}
public synchronized static void method() {
for (int i = 0; i < 5; i ++) {
try {
System.out.println(Thread.currentThread().getName() + ":" + (count++));
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public synchronized void run() {
method();
}
}
public class Demo00{
public static void main(String args[]){
SyncThread syncThread1 = new SyncThread();
SyncThread syncThread2 = new SyncThread();
Thread thread1 = new Thread(syncThread1, "SyncThread1");
Thread thread2 = new Thread(syncThread2, "SyncThread2");
thread1.start();
thread2.start();
}
}