如何使阻塞Java线程等待Tomcat中断

时间:2015-05-23 02:54:05

标签: java multithreading tomcat

我已将Tomcat嵌入JavaFX应用程序中。我需要Tomcat在我的应用程序生命周期内运行。

Thread.stop()已被弃用,因此我尝试使用其他方法,但这总是让我有异常

"Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException" on the line 74: tomcat.wait(500);.

 Caused by: java.lang.IllegalMonitorStateException
        at java.lang.Object.wait(Native Method)
        at webappgen.TomcatThread.run(WebServer.java:74)
        at webappgen.WebServer.Start(WebServer.java:22)
        at webappgen.Project.StartWebServer(Project.java:31)
        at webappgen.FXMLDocumentController.handleNewProjectAction(FXMLDocumentController.java:81)
        ... 56 more

以下是我的尝试:

package webappgen;

import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;


public class WebServer {

    TomcatThread thread;

    public WebServer(){

    }

    public void Start(String dir){

        thread = new TomcatThread(dir);
        thread.run();

    }

    public void Stop(){
        synchronized(TomcatThread.obj){
            thread.interrupt();
        }
    }
}


class TomcatThread extends Thread {
    public static final Object obj = new Object();
    private String dir;
    private volatile boolean stopServer = false;

    public void StopServer(boolean stop){
        this.stopServer = stop;
    }
    public TomcatThread(String dir){
        this.dir = dir;
    }
    @Override
    public void run() {
        String webappDirLocation = dir;
        Tomcat tomcat = new Tomcat();

        String webPort = "8083";
        tomcat.setPort(Integer.valueOf(webPort));

        try {
            tomcat.addWebapp("/", new File(webappDirLocation).getAbsolutePath());
        } catch (ServletException ex) {
            Logger.getLogger(WebServer.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.out.println("configuring app with basedir: " + new File(webappDirLocation).getAbsolutePath());

        try {
            tomcat.start();
        } catch (LifecycleException ex) {
            Logger.getLogger(WebServer.class.getName()).log(Level.SEVERE, null, ex);
        }

        synchronized(TomcatThread.obj){
            while(!stopServer){

                try {
                     tomcat.wait(500);

                } catch (InterruptedException ex) {
                       Logger.getLogger(TomcatThread.class.getName()).log(Level.SEVERE, null, ex);
                }

            }
        }
        try {
            tomcat.getServer().stop();
            tomcat.getServer().destroy();
        } catch (LifecycleException ex) {
            Logger.getLogger(TomcatThread.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
};

1 个答案:

答案 0 :(得分:0)

在线程启动后使用Thread.join()等待TomcatThread死掉;