在任务完成之前,我不知道如何让线程运行。 所以我有这个课程:
public class MainTest {
public static void main(String[] args){
ThreadRunnable t1 = new ThreadRunnable();
Thread t2 = new Thread(t1);
t2.start();
System.out.println(3);
//here the next code to run
}
}
另一个尝试例如在数据库中添加数据:
public class ThreadRunnable implements Runnable{
public void run(){
//code to make the thread waits until the insert is done
//code for inserting data in database
}
}
所以,在方法run()里面我需要类似的东西: - 尝试在数据库中插入数据 - 如果与数据库的连接断开,请等待5秒钟再试一次 - 如果连接正常,则插入数据,并返回添加数据的成功消息
这是可能的,如果可以,怎么样? 谢谢!
答案 0 :(得分:0)
您无需等待线程。只需在Runnable循环中重试:
public void run() {
try {
while (true) {
try {
// Do database operations here
// Succeeded
break;
} catch (SQLException e) {
// Failed; log exception and try again.
logger.log(Level.INFO, "Couldn't save data.", e);
}
// Wait before trying again.
Thread.sleep(5000);
}
} catch (InterruptedException e) {
logger.log(Level.INFO, "Interrupted; exiting.", e);
}
}
注意:中断是一个线程的显式请求,以停止正在进行的操作并自行终止。不应该在循环中捕获InterruptedException,因为希望循环在中断的情况下终止。
另一方面,你确实希望循环在SQLException的情况下继续执行,所以它应该被捕获到循环中。
答案 1 :(得分:-1)
你可以这样做:
1)在ThreadRunnable中添加waitFor函数 2)通过un LOCK变量添加同步
代码:
public class ThreadRunnable implements Runnable{
private boolean ended=false;
private final Object LOCK=new Object();
public void run(){
// do my stuff...
...
//at the end, notify the thread waiting for : it will wake up
synchronized(LOCK)
{
ended=true;
LOCK.notifyAll();
}
}
/**
Waits until the task is done
*/
public void waitFor()
{
synchronized(LOCK)
{
while(!ended)
{
//sleeps until notifAll is called (see run())
wait();
}
}
}
}
(在此代码中,您必须为InterruptedException添加try / catch) 在你的主要:
public class MainTest {
public static void main(String[] args){
ThreadRunnable t1 = new ThreadRunnable();
Thread t2 = new Thread(t1);
t2.start();
t1.waitFor();
System.out.println(3);
//here the next code to run
}
}