标签:线程池 thread 线程同步 countdownlatch
业务逻辑:
一个大型社区,每一秒有上千人在提交留言,提交的留言将经过,上万条的正则表达式的过滤,没有匹配任何规则的,才保存到系统,否则提示用户,您录入的内容不合法。
我是这样想的,把这上万条正则表达式,拆分成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; } @Override public 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(); } }
标签:线程池 thread 线程同步 countdownlatch
原文地址:http://blog.csdn.net/danielinbiti/article/details/44963423