Home > Database > Mysql Tutorial > 编写线程安全的JSP程序_MySQL

编写线程安全的JSP程序_MySQL

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-01 14:09:12
Original
1276 people have browsed it

作者:徐春金


   
      String inssql = "insert into buy(empid, name, dept) values (?, ?, ?,?)";
      stmt = conn.prepareStatement(inssql);

      stmt.setString(1, name);
      stmt.setString(2, procuct);   
      stmt.setInt(3, quantity);
      stmt.execute();
    }

    catch (Exception e)
    {
        System.out.println("SQLException was thrown: " + e.getMessage());
    }
    finally //close connections and     {
        try {
          if(stmt != null)
            stmt.close();
          if(conn != null)
            conn.close();
        } catch (SQLException sqle) {
            System.out.println("SQLException was thrown: " + sqle.getMessage());
        }
    }
}
%>


在该JSP文件中加上: ,使它以单线程方式执行,这时,仍然只有一个实例,所有客户端的请求以串行方 式执行。这样会降低系统的性能.

  • 对函数savebuy()加synchronized进行线程同步,该JSP仍然以多线程方式执行,但也会降低系统的性能
    public synchronized void savebuy()
    {
           ......
    }
  • 采用局部变量代替实例变量,函数savebuy()声明如下:
    因为在savebuy()中使用的是传给他的形参,是在堆栈中分配的,所以是线程安全的.
    public void savebuy(String name,String product, int quantity)
    {
          ......
    }

    调用方式改为:
    String name
    String product;
    long quantity;

    name=request.getParameter("name");
    product=request.getParameter("product");
    quantity=request.getParameter("quantity");
    savebuy(name,product,quantity)
    %>

  • Related labels:
    source:php.cn
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template