WEB开发网
开发学院软件开发Java 多线程设计模式 -- suspension 阅读

多线程设计模式 -- suspension

 2009-09-17 00:00:00 来源:WEB开发网   
核心提示: PriorityBlockingQueue:类似于LinkedBlockingQueue,但其所含对象的 排序不是FIFO,多线程设计模式 -- suspension(4),而是依据对象的自然排序顺序或者是构造函数所带的Comparator 决定的顺序, SynchronousQueue:特殊的

PriorityBlockingQueue:类似于LinkedBlockingQueue,但其所含对象的 排序不是FIFO,而是依据对象的自然排序顺序或者是构造函数所带的Comparator 决定的顺序。

SynchronousQueue:特殊的BlockingQueue,对其的操作必须是放和取交替完成的。

客户线程

Java代码   

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

服务器线程

Java代码   

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

测试类

Java代码

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

上一页  1 2 3 4 

Tags:线程 设计模式 suspension

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接