您的位置:首页 > 其它

线程之旅--Single Threaded Execution Pattern

2007-10-08 21:38 344 查看
假设有这样一个环境,有个门,门的宽度恰好只能容许一个人经过,若又2个人同时进门,那么门的宽度将不符合

Single Threaded Execution Pattern 指的是一个线程执行的场所,就像上面所说的独木桥一样,这个模式用来限制同时只能让一个线程运行。加入synchronized修饰符修饰的方法,就只能让这个方法同一时刻只有一个线程能访问,大家可以试试,把Gate类的相关的方法的synchronized修饰符去掉了,会是什么效果

下面我们用个简单的例子来进行说明(范例由3个文件组成):

--------------------Main.java --主程序调用-并让3个人不断的进出门

public class Main {

public static void main(String[] args) {

System.out.println("开始, 按 CTRL+C to exit.");

Gate gate = new Gate();

new UserThread(gate, "湖北人", "湖北").start();

new UserThread(gate, "广州人", "广州").start();

new UserThread(gate, "浙江人", "浙江").start();

}

}

------------------Gate.java --当人进出时,会记录人的姓名和籍贯

public class Gate {

private int counter = 0;

private String name = "Nobody";

private String address = "Nowhere";

public synchronized void pass(String name, String address) {

this.counter++;

this.name = name;

this.address = address;

check();

}

public synchronized String toString() {

return "No." + counter + ": " + name + ", " + address;

}

private void check() {

if (name.charAt(0) != address.charAt(0)) {

System.out.println("***** BROKEN ***** " + toString());

}

}

}

}

--------------------UserThread--人的类,负责不断的在门间穿梭

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

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: