public class VoteTest extends HttpServlet {
VoteSystem voteSystem = new VoteSystem();
...
doPost(...){
...
voteSystem.vote(Integer.parseInt(request.getParameter("number")));
...
}
}public class VoteSystem {
public void vote(int id) {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = getConnection();
con.setAutoCommit(false);
pstmt = con
.prepareStatement("update voteGUI set count=count+1 where ID=?;");
pstmt.setInt(1, id);
synchronized (this) {
pstmt.execute();
con.commit();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
pstmt.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
....
}
这是一个投票,数据库是mysql,ID是选项,count是票数,请教各位,是否有必要设置synchronized避免投票并发问题,如果要设置,怎么设置才能提高性能,小弟感觉只是严重匮乏,求高手帮助,请教解决这个问题需要补充哪一方面的知识
VoteSystem voteSystem = new VoteSystem();
...
doPost(...){
...
voteSystem.vote(Integer.parseInt(request.getParameter("number")));
...
}
}public class VoteSystem {
public void vote(int id) {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = getConnection();
con.setAutoCommit(false);
pstmt = con
.prepareStatement("update voteGUI set count=count+1 where ID=?;");
pstmt.setInt(1, id);
synchronized (this) {
pstmt.execute();
con.commit();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
pstmt.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
....
}
这是一个投票,数据库是mysql,ID是选项,count是票数,请教各位,是否有必要设置synchronized避免投票并发问题,如果要设置,怎么设置才能提高性能,小弟感觉只是严重匮乏,求高手帮助,请教解决这个问题需要补充哪一方面的知识
// 在 run 方法中使用了就会产生线程安全问题
// 这里的 Object
private List<String> list; public MyRunnable(List<String> list) {
this.list = list;
} public void run() {
// todo
}
}