標籤:線程池 thread 線程同步 countdownlatch
商務邏輯:
一個大型社區,每一秒有上千人在提交留言,提交的留言將經過,上萬條的Regex的過濾,沒有匹配任何規則的,才儲存到系統,否則提示使用者,您錄入的內容不合法。
我是這樣想的,把這上萬條Regex,拆分成2000條一組,開一個5個線程的線程池,每個線程將負責其中2000個規則的匹配。
每條留言提交時,將由這5個線程,去判斷是否有匹配的規則,如果其中一個線程匹配到了規則,將結束其他4個線程的任務,返回給使用者結果。
==
代碼:
import java.util.ArrayList;import java.util.concurrent.CountDownLatch;public class TestThread {/** * @param args * @throws InterruptedException */public static void main(String[] args) throws InterruptedException {String c = "評論1";TxtClass tx = new TxtClass(c);CountDownLatch cdLatch = new CountDownLatch(5); Thread tr = new CRThread(1,tx,cdLatch);//1表示第一個 Thread tr2 = new CRThread(2,tx,cdLatch); Thread tr3 = new CRThread(3,tx,cdLatch); Thread tr4 = new CRThread(4,tx,cdLatch); Thread tr5 = new CRThread(5,tx,cdLatch); tr.start(); tr2.start(); tr3.start(); tr4.start(); tr5.start(); cdLatch.await(); System.out.println("都執行完了,結果["+tx.isFind() + "]");}}class TxtClass{private String c = "";private boolean isFind = false;public TxtClass(String c){this.c = c;}public boolean isFind() {return isFind;}public void setFind(boolean isFind) {this.isFind = isFind;}public String getC() {return c;}}class RegClass{//校正規則private static RegClass rc = new RegClass();public static RegClass getInstance(){return rc;}private ArrayList<String> list = new ArrayList();public RegClass(){//初始化規則list.add("s");list.add("s");list.add("s");list.add("s");list.add("s");list.add("s");list.add("s");list.add("s");list.add("s");list.add("s");list.add("s");list.add("s");list.add("s");list.add("s");list.add("s");list.add("s");list.add("s");list.add("s");list.add("s");list.add("s");list.add("1");list.add("評");list.add("a");list.add("b");list.add("r");}public boolean isContains(int index,String c){if(list.size()>index){return c.indexOf(list.get(index))>=0;}else{return false;}}}class CRThread extends Thread{private int startNum = 0;private TxtClass txtClass;//留言內容private CountDownLatch cdLatch;private int oneLength = 2000;//一個線程校正的長度public CRThread(int i,TxtClass txtClass,CountDownLatch cdLatch){super();this.startNum = i;this.txtClass = txtClass;this.cdLatch = cdLatch;}@Overridepublic void run() {boolean f = false;int nums = 0;for(int i=0;i<oneLength;i++){nums = (startNum-1)*oneLength+i;System.out.println("thread-"+startNum+"-["+nums+"]");f=RegClass.getInstance().isContains(nums, txtClass.getC());if(f){txtClass.setFind(true);}if(txtClass.isFind()){break;}try {Thread.sleep(1);} catch (InterruptedException e) {e.printStackTrace();}}System.out.println("thread-"+startNum+"-結束["+nums+"]");this.cdLatch.countDown();}}
java線程同步