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

JAVA多线程设计方式三 Guarded Suspension Pattern

2012-06-28 
JAVA多线程设计模式三 Guarded Suspension Pattern一定要满足的条件? Guard Condition ,警戒条件。?public

JAVA多线程设计模式三 Guarded Suspension Pattern

一定要满足的条件? Guard Condition ,警戒条件。

?

public class Request {    private final String name;    public Request(String name) {        this.name = name;    }    public String getName() {        return name;    }    public String toString() {        return "[ Request " + name + " ]";    }}

?

?

?

public class RequestQueue {    private final LinkedList queue = new LinkedList();    public synchronized Request getRequest() {        while (queue.size() <= 0) {            try {                                                   wait();            } catch (InterruptedException e) {                  }                                               }                                                   return (Request)queue.removeFirst();    }    public synchronized void putRequest(Request request) {        queue.addLast(request);        notifyAll();    }}

?

?

public class ClientThread extends Thread {    private Random random;    private RequestQueue requestQueue;    public ClientThread(RequestQueue requestQueue, String name, long seed) {        super(name);        this.requestQueue = requestQueue;        this.random = new Random(seed);    }    public void run() {        for (int i = 0; i < 10000; i++) {            Request request = new Request("No." + i);            System.out.println(Thread.currentThread().getName() + " requests " + request);            requestQueue.putRequest(request);            try {                Thread.sleep(random.nextInt(1000));            } catch (InterruptedException e) {            }        }    }}

?

?

public class ServerThread extends Thread {    private Random random;    private RequestQueue requestQueue;    public ServerThread(RequestQueue requestQueue, String name, long seed) {        super(name);        this.requestQueue = requestQueue;        this.random = new Random(seed);    }    public void run() {        for (int i = 0; i < 10000; i++) {            Request request = requestQueue.getRequest();            System.out.println(Thread.currentThread().getName() + " handles  " + request);            try {                Thread.sleep(random.nextInt(1000));            } catch (InterruptedException e) {            }        }    }}

?

?

?

public class Main {    public static void main(String[] args) {        RequestQueue requestQueue = new RequestQueue();        new ClientThread(requestQueue, "Alice", 3141592L).start();        new ServerThread(requestQueue, "Bobby", 6535897L).start();    }}

?

?

理解为 带条件的同步关键字。 wait / notify

?

?

1、while(!ready){      wait();}ready = true;notifyAll();2、while(!ready){     Thread.yield();}ready=true;

?

注:Thread.yield(); 不会解除锁定,所以这句不应该放在同步关键字中。 ready 声明为 volatile

热点排行