实现Callable或Runnable接口,实现他们对应的方法
接口定义
#Callable接口
public interface Callable<V> {
V call() throws Exception;
}
#Runnable接口
public interface Runnable {
public abstract void run();
}
相同点
都是接口
都可以编写多线程程序
都采用Thread.start()启动线程
不同点
Runnable没有返回值;Callable可以返回执行结果,是个泛型,和Future、FutureTask配合可以用来获取异步执行的结果
Callable接口的call()方法允许抛出异常;Runnable的run()方法异常只能在内部消化,不能往上继续抛
注:Callalble接口支持返回执行结果,需要调用FutureTask.get()得到,此方法会阻塞主进程的继续往下执行,如果不调用不会阻塞
自定义调用记录,我需要实现短信的多线程发送还要判断返回值是否成功
多线程实现层
public ExecutorService executorService = Executors.newCachedThreadPool();
@Override//当前方法没返回值
public void sendMessage(String numbers, String content,
String signature) {
new Thread(new SendThread(numbers, content, signature)).start();
}
@Override//次方法有返回值
public String sendMultiMessage(String numbers, String content,
String signature, String sendCode) {
Future<String> result = executorService.submit(new FutureMessage(numbers, content, signature, sendCode));
try {
return result.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
return "";
}
初始话FutureMessage类,FutureMessage类实现了callable
public class FutureMessage implements Callable<String> {
SendMessage sendMessage;
String phoneNums;
String content;
String signature;
String sendCode;
public FutureMessage(String phoneNums, String content, String signature,String sendCode) {
this.phoneNums = phoneNums;
this.content = content;
this.signature = signature;
this.sendCode = sendCode;
}
@Override
public String call() {
String[] phoneNum = phoneNums.split(",");
String smsContent = content;
// if (content.length() > 140) {
// smsContent = content.substring(0,140);
// }
String sendStatus = "";
//默认状态是1,发送成功的时候修改状态为0,异常时send值为2
for (int i = 0; i < phoneNum.length; i++) {
sendMessage = new SendMessage();
int send = 1;
try {
send = sendMessage.send(phoneNum[i], smsContent,this.sendCode);
} catch (IOException e) {
e.printStackTrace();
send = 2;
}
if (sendStatus.equals("")) {
sendStatus = sendStatus + phoneNum[i] + ":" + send;
} else {
sendStatus = sendStatus + "," + phoneNum[i] + ":" + send;
}
}
return sendStatus;
}
}
至此进入短信发送的方法send
第二种SendThread类实现了Runnable没有返回值的线程调用,方法如下
public class SendThread implements Runnable {
SendMessage sendMessage;
String phoneNums;
String content;
String signature;
public SendThread(String phoneNums, String content, String signature) {
this.phoneNums = phoneNums;
this.content = content;
this.signature = signature;
}
@Override
public void run() {
String[] phoneNum = phoneNums.split(",");
String smsContent = content;
if (content.length() > 120) {
smsContent = content.substring(120);
}
for (int i = 0; i < phoneNum.length; i++) {
sendMessage = new SendMessage();
try {
sendMessage.send(phoneNum[i], smsContent, "");
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
//每两次内容发送间间隔10秒,以免短信顺序错误
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}