標籤:
Worker pattern[工作模式]
一:Worker pattern的參與者
--->Client(委託人線程)
--->Channel(通道,裡邊有,存放請求的隊列)
--->Request(工作內容的封裝)
--->Worker(工人線程)
二:Worker pattern模式什麼時候使用
--->類似生產者消費者
三:Worker pattern思考
四進階說明
--->背景工作執行緒取出請求內容封裝後,根據多態,不同的請求執行不同的業務方法
Request介面
1 package com.yeepay.sxf.thread7; 2 /** 3 * 抽象請求 4 * @author sxf 5 * 6 */ 7 public interface Request { 8 //定義的抽象方法 9 public void eat();10 }View Code
不同Request介面的實作類別
人的請求封裝
1 package com.yeepay.sxf.thread7; 2 /** 3 * 人的請求 4 * @author sxf 5 * 6 */ 7 public class PersonRequest implements Request{ 8 //姓名 9 private String name;10 //事物11 private String food;12 13 14 public PersonRequest(String name, String food) {15 super();16 this.name = name;17 this.food = food;18 }19 20 21 @Override22 public void eat() {23 24 System.out.println("PersonRequest.eat()"+name+"吃掉"+food);25 fell();26 }27 28 public void fell(){29 System.out.println("PersonRequest.fell()"+"我吃飽了");30 }31 32 33 public String getName() {34 return name;35 }36 37 38 public void setName(String name) {39 this.name = name;40 }41 42 43 public String getFood() {44 return food;45 }46 47 48 public void setFood(String food) {49 this.food = food;50 }51 52 53 54 }View Code
貓的請求封裝
1 package com.yeepay.sxf.thread7; 2 /** 3 * 貓的請求 4 * @author sxf 5 * 6 */ 7 public class CatRequest implements Request{ 8 //姓名 9 private String name;10 //年齡11 private int age;12 13 14 public CatRequest(String name, int age) {15 super();16 this.name = name;17 this.age = age;18 }19 20 21 @Override22 public void eat() {23 // TODO Auto-generated method stub24 System.out.println("CatRequest.eat()"+name+"有"+age+"月大");25 26 }27 28 29 public String getName() {30 return name;31 }32 33 34 public void setName(String name) {35 this.name = name;36 }37 38 39 public int getAge() {40 return age;41 }42 43 44 public void setAge(int age) {45 this.age = age;46 }47 48 49 50 }View Code
類比背景工作執行緒取出請求,執行不同的業務
1 package com.yeepay.sxf.thread7; 2 /** 3 * 背景工作執行緒 4 * @author sxf 5 * 6 */ 7 public class Test { 8 9 public static void main(String[] args) {10 11 //類比線程取出不同的的請求封裝12 Request peRequest=new PersonRequest("尚曉飛", "漢堡");13 Request catRequest=new CatRequest("黑貓警長", 3);14 //不同的請求封裝利用多態調用方法,實現不同的業務15 peRequest.eat();16 catRequest.eat();17 }18 19 }View Code
列印結果
PersonRequest.eat()尚曉飛吃掉漢堡
PersonRequest.fell()我吃飽了
CatRequest.eat()黑貓警長有3月大
多線程程式設計學習(9)worker pattern模式