可以类似下面这样
import java.util.ArrayList;
import java.util.concurrent.CountDownLatch;
public class TestThread {
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);
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();
}
}