Java 在它的 run() 中调用线程

标签 java thread-safety

我编写了一个线程类,通过每秒发送一个小字符串来检查与服务器的套接字连接。

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/

相关文章:

java - 套接字上并发读写的线程安全

c++ - volatile 可能是用户定义的类型,以帮助编写线程安全的代码

java - 在调用remove()之前检查队列是否还有剩余内容

java - @New注解不起作用

java - 带有扩展超过一种类型的参数的列表

java - 我怎样才能实现一个简单的 AsyncTaskLoader?

java - 如何修复我的 java.lang.NullPointerException (android)?

c++ - 为什么使用原子 CAS 的程序不能保持线程安全?

.net - 以同一方法写入两个 .net 字典时的线程安全

java - 如何检查项目是否包含启动快捷方式的特定文件