论坛首页 Java企业应用论坛

多线程设计模式--single threaded execution

浏览 2126 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2009-07-08   最后修改:2009-07-08

调用线程
public class UserThread extends Thread {
    private final Gate gate;
    private final String myname;
    private final String myaddress;
    public UserThread(Gate gate, String myname, String myaddress) {
        this.gate = gate;
        this.myname = myname;
        this.myaddress = myaddress;
    }
    public void run() {
        System.out.println(myname + " BEGIN");
        while (true) {
            gate.pass(myname, myaddress);
        }
    }
}


同时只允许一个对象访问锁块.(类似于synchronized 标示的块)
这样做的主要原因是因为保护类变量不同时被多个线程修改
方法内部的变量不会在多线程同时修改.

任务
public class Gate {
	private int counter = 0;
	private String name = "Nobody";
	private String address = "Nowhere";
	//jdk1.5新特性 效率高于synchronized 
         private Lock passLock = new ReentrantLock();

	private Lock toStringLock = new ReentrantLock();

	public void pass(String name, String address) {
		//使用锁机制
                  passLock.lock();
		try {
			this.counter++;
			this.name = name;
			this.address = address;
			check();
		} finally {
		    //解锁	
                      passLock.unlock();
		}
	}

	public String toString() {
		toStringLock.lock();
		try {
			return "No." + counter + ": " + name + ", " + address;
		} finally {
			toStringLock.unlock();
		}
	}

	private void check() {
		if (name.charAt(0) != address.charAt(0)) {
			System.out.println("***** BROKEN ***** " + toString());
		}
	}
}



主程序
public class Main {
    public static void main(String[] args) {
        System.out.println("Testing Gate, hit CTRL+C to exit.");
        Gate gate = new Gate();
        new UserThread(gate, "Alice", "Alaska").start();
        new UserThread(gate, "Bobby", "Brazil").start();
        new UserThread(gate, "Chris", "Canada").start();
    }
}
   发表时间:2009-07-08  
JDK5新增了一个很实用的多线程并发包java.util.concurrent,
用他来做多线程开发会更高效和简洁~
0 请登录后投票
   发表时间:2009-07-23  
LZ 要是能用JAVA5的多线程机制描述一下就好了。
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics