这一章节我们来介绍同步阻塞、synchronized和volatile。

1.同步阻塞

之前我们提到过synchronized放在同步方法上:

public synchronized void transfer(int fromAccount, int toAccount,
			double money) {
		if (accounts[fromAccount] < money) {
			return;
		}
		accounts[fromAccount] -= money;
		System.out.printf("从" + fromAccount + "账户转出%10.2f元,", money);
		accounts[toAccount] += money;
		System.out.printf("从" + toAccount + "账户转入%10.2f元,", money);
		System.out.printf("总数:%10.2f元", getTotal());
		System.out.println();
	}


其实他的等价代码是这样的:

private Object lock = new Object();

	public void transfer(int fromAccount, int toAccount, double money) {
		synchronized (lock) {
			if (accounts[fromAccount] < money) {
				return;
			}
			accounts[fromAccount] -= money;
			System.out.printf("从" + fromAccount + "账户转出%10.2f元,", money);
			accounts[toAccount] += money;
			System.out.printf("从" + toAccount + "账户转入%10.2f元,", money);
			System.out.printf("总数:%10.2f元", getTotal());
			System.out.println();
		}
	}


上面的lock扮演的就是我们平常所说的那把锁,只有持有这把锁,线程才能进入方法进行操作,而synchronized就是控制这把锁一次只能给一个线程持有,从而实现同步阻塞。

 

2. volatile

volatile是另一种实现线程阻塞的方法,但是他具有局限性:就是只完成变量赋值,而不执行其他操作。

可行的方式:

package com.ray.ch17;

public class Test {
	private volatile boolean isDone;

	public boolean isDone() {
		return isDone;
	}

	public void setDone(boolean isDone) {
		this.isDone = isDone;
	}

}

等价代码:

package com.ray.ch17;

public class Test {
	private boolean isDone;

	public synchronized boolean isDone() {
		return isDone;
	}

	public synchronized void setDone(boolean isDone) {
		this.isDone = isDone;
	}

}


不可行的方式:

package com.ray.ch17;

public class Test {
	private volatile boolean isDone;

	public void flipDone() {
		isDone = !isDone;
	}
}



总结:这一章节主要介绍同步阻塞和volatile的使用情况。