如何防止Runnable类崩溃应用程序?

时间:2016-06-19 02:23:22

标签: java jdbc thread-safety

我正在尝试使用Threads实现(更强大)健壮的应用程序。

我的JdbcAccess.java更相关的部分是:

protected ResultSet readfromSQLServer(String url, String instance, String port, String database, String user, String passwd, String query) throws Exception {
    try {
        // This will load the SQLServer driver
        Class.forName("net.sourceforge.jtds.jdbc.Driver");

        // Setup the connection with the DB
        String connectionUrl = "";

        if (instance != null || instance == "") {
            connectionUrl = "jdbc:jtds:sqlserver://" + url +  ":" + port + "/" + database + ";instance=" + instance + ";user=" + user + ";password=" + passwd;
        } else {
            connectionUrl = "jdbc:jtds:sqlserver://" + url +  ":" + port + "/" + database + ";user=" + user + ";password=" + passwd;
        }

        start();

        connection = DriverManager.getConnection(connectionUrl);

        // Statements allow to issue SQL queries to the database
        statement = (Statement) connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);

        resultSet = statement.executeQuery(query);
    } catch (Exception e) {
        e.printStackTrace();
    } 

    return resultSet;
}

public void run() {
    System.out.println("Running JdbcAccess thread");
    try {
        // Let the thread sleep for a while.
        Thread.sleep(50);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

public void start () {
    System.out.println("Starting JdbcAccess thread");
    if (thread == null) {
        thread = new Thread (this);
        thread.start ();
    }
}

问题是,如果它有一个有缺陷的SQL查询,整个应用程序崩溃,而不是只是线程失败/消失的预期结果。

我在这里做错了什么?

0 个答案:

没有答案