需求:
启动一个线程,循环取一数据库表的记录(可以设为每5S取一次),取出一条作为短信发给电信短信网关,应为没做过Java的awt swing 最好能用CMD 控制台解决启动和停止的命令?
不清楚这个是要起2个线程(一个main线程,一个发短信线程),还是多个线程(一个main线程,N个发短信线程)?
有经验的请赐教!
启动一个线程,循环取一数据库表的记录(可以设为每5S取一次),取出一条作为短信发给电信短信网关,应为没做过Java的awt swing 最好能用CMD 控制台解决启动和停止的命令?
不清楚这个是要起2个线程(一个main线程,一个发短信线程),还是多个线程(一个main线程,N个发短信线程)?
有经验的请赐教!
发短信线程里写一个while(true)死循环
设一直全局的控制FLAG来控制线程何时挂起,何时唤醒
public class MainApp { public static void main(String[] args) {
try {
MySprite dog = new MySprite("狗狗"); System.out.println("--- start sprites");
dog.start(); Thread.sleep(500);
System.out.println("--- suspend dog");
dog.suspend();
System.out.println("--- main thread do something");
Thread.sleep(500);
System.out.println("--- resume dog");
dog.resume();
Thread.sleep(500);
System.out.println("--- end dog");
dog.stop();
System.out.println("--- main thread do something");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}线程实现public class MySprite implements Runnable { /**//*
* 线程用变量
*/
private boolean running = false;
private boolean waiting = false;
private Thread thread;
/**//*
* Business 变量
*/
private String name;
public MySprite(String name) {
this.name = name;
this.thread = new Thread(this);
}
/** *//**
* 启动线程
*/
public void start() {
running = true;
thread.start();
}
/** *//**
* 挂起线程
*/
public void suspend() {
if (waiting) { // 是挂起状态则直接返回
return;
}
synchronized (this) {
this.waiting = true;
}
}
/** *//**
* 恢复线程
*/
public void resume() {
if (!waiting) { // 没有挂起则直接返回
return;
}
synchronized (this) {
this.waiting = false;
this.notifyAll();
}
}
/** *//**
* 停止线程
*/
public void stop() {
if (!running) { // 没有运行则直接返回
return;
}
synchronized (this) {
running = false;
}
}
public void run() {
for(;;) {
try {
// 线程挂起和退出处理
synchronized (this) {
if (!running) {
break;
}
if (waiting) {
this.wait();
}
} // 应该做的事情
cry();
// 进入等待状态
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void cry() {
System.out.println(name + ":woo!");
}
}从谷歌那抄来的代码,提供LZ参考
while(true) {
try {
// 线程挂起和退出处理
synchronized (this) {
if (!running) {
break;
}
if (waiting) {
this.wait();
}
} // 应该做的事情
cry();
// 进入等待状态
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void run(){
while(true){
Thread.sleep(你的时间)//注意性能,还有内存管理 防止程序崩溃
//执行查询
}
}
}