首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件开发 >

JAVA多线程设计形式一 Single Threaded Execution

2012-07-05 
JAVA多线程设计模式一 Single Threaded Executionpublic class Gate {private int counter 0private St

JAVA多线程设计模式一 Single Threaded Execution

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;try {Thread.sleep(1000);} catch (InterruptedException e) {}this.address = address;check();}public  String toString() {return "No." + counter + ": " + name + ", " + address;}private void check() {if (name.charAt(0) != address.charAt(0)) {System.out.println("***** BROKEN ***** " + toString());}}}

?

?

?

?

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

?

?

?

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

?

Gate 类中的方法,同步关键字的有无。 执行程序看看。

热点排行