有个项目中用到发短信的功能,要求能短信群发,然后由另一线程去执行短信发送功能实现如下:
- Java code
public class SendSmsDemo extends Thread { private static SmsHandler smsHandler; private static BlockingQueue<SMS> queue = new LinkedBlockingQueue<SMS>(); private static SendSmsDemo instance = null; private SendSmsDemo() { } public synchronized static SendSmsDemo getInstance(SmsHandler handler) { if (instance == null) { System.out.println("new instatnce..."); instance = new SendSmsDemo(); instance.setDaemon(true); smsHandler = handler; instance.start(); } return instance; } public void add(SMS sms) { queue.add(sms); } @Override public void run() { while(true){ SMS sms=new SMS(); try { sms = queue.take(); } catch (InterruptedException e) { e.printStackTrace(); } smsHandler.sendSMS(sms); } }}
每次要发短息的时候实际是执行demo=SendSmsDemo.getinstance() demo.add(sms)
各位看以下有什么问题,或更好的方式。
------解决方案--------------------
用BlockingQueue 存放数据 用多线程进行短信发送
------解决方案--------------------
问题很大啊。。。
1、 while(true)。。。
线程创建了后,不能结束,也就意味着线程资源永远不能回收。。。
2、SMS sms=new SMS(); 。。。
不明白为什么要new这个SMS对象.
3、try {
sms = queue.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
smsHandler.sendSMS(sms);
队列中一定有sms吗?
这种消息队列处理,可以参考下生产者消费者模式。
------解决方案--------------------
------解决方案--------------------
queue.take() 如果 Queue 中没有对象的话,会在这里一直待着,直到产生中断为止。
楼主代码改进的地方有很多:
- Java code
while(true){ SMS sms=new SMS(); try { sms = queue.take(); } catch (InterruptedException e) { e.printStackTrace(); } smsHandler.sendSMS(sms); }
------解决方案--------------------
不太会了