`
daichangfu
  • 浏览: 260330 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

不使用synchronized模拟Single Threaded Execution Pattern

    博客分类:
  • java
阅读更多
public class Gate {
    private int counter = 0;
    private String name = "Nobody";
    private String address = "Nowhere";
    private final Mutex mutex = new Mutex();
    public void pass(String name, String address) { // 并非synchronized
        mutex.lock();
        try {
            this.counter++;
            this.name = name;
            this.address = address;
            check();
        } finally {
            mutex.unlock();
        }
    }
    public String toString() { // 并非synchronized
        String s = null;
        mutex.lock();
        try {
            s = "No." + counter + ": " + name + ", " + address;
        } finally {
            mutex.unlock();
        }
        return s;
    }
    private void check() {
        if (name.charAt(0) != address.charAt(0)) {
            System.out.println("***** BROKEN ***** " + toString());
        }
    }
}


public final class Mutex {
	private boolean basy = false;
	
	public synchronized void lock(){
		while (basy) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		basy = true;
	}
	
	public synchronized void unlock(){
		basy = false;
		notifyAll();
	}
	
	
}
 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics