在工作中,我们可能会面临一个比较耗时的任务处理。比如给10万个手机号码发送短信,如果使用单线程的话是很费时的,如果一个手机号码短信的发送操作需要1s,那么大概需要1天。如果使用10个线程一起发送,那么只需要0.1天左右。那么怎么判断这10个线程都将短信发送完成了呢?一下分享目前所了解到的几个方法。
1)通过数组处理
public class ThreadHandleDemo {
//假设有五个线程
private static volatile boolean[] arr = new boolean[]{false,false,false,false,false};
public static void main(String[] args) {
for(int i = 0; i < 5; i++){
Thread thread = new ThreadHandler(i);
thread.start();
}
//通过循环遍历 arr数组的状态 判断整个任务是否完成
while(true){
boolean finished = true;
for(int i = 0; i < 5; i++){
if(arr[i] == false){
finished = false;
break; //跳出for循环
}
}
if(finished){
break; //全部线程执行完成 跳出while循环
}
}
System.out.println("all finished ....");
}
static class ThreadHandler extends Thread{
private int threadNum;
public ThreadHandler(int num){
this.threadNum = num;
}
@Override
public void run() {
try {
Thread.sleep(2000); //模拟任务所花费的时间
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程"+threadNum +"已经完成任务");
arr[threadNum] = true;
}
}
}
//线程1已经完成任务
//线程0已经完成任务
//线程4已经完成任务
//线程3已经完成任务
//线程2已经完成任务
//all finished ....
数组需要使用volatile保证数据的可见性。
2.使用Thread.join()方法
public class JoinHandlerDemo {
public static void main(String[] args) throws InterruptedException {
Thread[] threads = new Thread[5];
for(int i = 0; i < 5; i++){
Thread thread = new JoinHandler(i);
thread.start();
threads[i] = thread;
}
for(int i = 0; i < threads.length; i++){
threads[i].join();
}
System.out.println("all finished....");
}
static class JoinHandler extends Thread{
private int threadNum;
public JoinHandler (int num){
this.threadNum = num;
}
@Override
public void run() {
try {
Thread.sleep(2000); //模拟任务耗时操作
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程" + threadNum + "已经完成任务");
}
}
}
//线程2已经完成任务
//线程0已经完成任务
//线程4已经完成任务
//线程1已经完成任务
//线程3已经完成任务
//all finished....
创建之后就启动线程,线程都启动之后使用join方法。join方法会让主线程等待子线程执行完成,但是各个子线程是互不影响的
3.使用并发包下的CountDownLatch的await(),countDown()方法联合使用达到目的
实现方式:https://blog.csdn.net/xindanding/article/details/103854191