我编写了一个线程类,通过每秒发送一个小字符串来检查与服务器的套接字连接。
begin()
方法执行线程。
连接丢失后,线程会再次尝试连接。
我的问题是是否可以像我一样通过 begin()
方法重新运行 run()
方法中的线程(见下文)。
public void begin() {
Check = new Thread(this);
Check.start();
}
@Override
public void run() {
Thread thisThread = Thread.currentThread();
while (Check==thisThread) {
try {
oos.writeObject("a");
// oos.flush();
synchronized (this) {
while (pleaseWait) {
try {
System.out.println("waiting");
wait();
System.out.println("not waiting");
}
catch (Exception e) {
System.err.println("Thread is interrupted: "+e.getMessage());
}
}
}
sleep(1000);
} catch (Exception ex) {
v = new Visual("The connection is lost. The system will try to reconnect now.");
this.end();
try {
Server=ClientLogin.checkingServers(); //returns the reachable server string address
socket = new Socket(Server, ServerPort);
System.out.println("Connected: " + socket);
oos = new ObjectOutputStream(socket.getOutputStream());
begin();
v = new Visual("The system is reconnected.");
}
catch(UnknownHostException uhe){
System.out.println("Host unknown: " + uhe.getMessage());
v = new Visual("The system has failed to reconnected.");
}
catch (IOException ioe) {
System.out.println("The system cannot connect to servers: " + ioe.getMessage());
v = new Visual("The system has failed to reconnected.");
}
catch (Exception e) {
System.out.println("The system has failed to reconnect: " + e.getMessage());
v = new Visual("The system has failed to reconnected.");
}
}
}
}
public void end() {
Check = null;
}
最佳答案
我不知道为什么那行不通,但它看起来有点乱。您可能必须将 Check
声明为 volatile
以确保循环始终读取当前值,以防新线程覆盖它。
恕我直言,更好的方法是一个单独的“主管”线程,它负责启动其中一个线程,然后使用 Thread.join()
等待它结束,此时它可以重新启动它。
通过这种方式,您的主线程逻辑可以专注于它应该做的事情,而不需要有任何“ self 意识”。
关于Java 在它的 run() 中调用线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12239787/