Advertisement
Guest User

Untitled

a guest
Apr 28th, 2016
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.98 KB | None | 0 0
  1. private static Connection conectar(){
  2. try {
  3. Class.forName("com.mysql.jdbc.Driver");
  4. return DriverManager.getConnection("jdbc:mysql://localhost/fiscal", "jp", "");
  5. } catch (ClassNotFoundException ex) {
  6. Logger.getLogger(Concorrencia.class.getName()).log(Level.SEVERE, null, ex);
  7. } catch (SQLException ex) {
  8. Logger.getLogger(Concorrencia.class.getName()).log(Level.SEVERE, null, ex);
  9. }
  10. return null;
  11. }
  12.  
  13. private static int getProximoId(Connection con, int cupomId) throws SQLException{
  14. PreparedStatement stmt = con.prepareStatement("select max(nr_item) from item_cupom where cupom_id = ?");
  15. stmt.setInt(1, cupomId);
  16. ResultSet rs = stmt.executeQuery();
  17. try{
  18. if(rs.next()){
  19. return rs.getInt(1) + 1;
  20. }else{
  21. return 1;
  22. }
  23. }finally{
  24. rs.close();
  25. stmt.close();
  26. }
  27. }
  28.  
  29. public static void inserirItem(Connection con, int cupomId, boolean demorar) throws SQLException, InterruptedException{
  30. int nrItem = getProximoId(con, cupomId);
  31. if(demorar){
  32. Thread.sleep(200);
  33. }
  34. PreparedStatement pstmt = con.prepareStatement("insert into item_cupom(cupom_id, nr_item) values(?, ?);");
  35. pstmt.setInt(1, cupomId);
  36. pstmt.setInt(2, nrItem);
  37. pstmt.execute();
  38. pstmt.close();
  39. }
  40.  
  41. private static boolean seraQueVaiDemorar(){
  42. double valor = Math.random();
  43. return valor > 0.8;
  44. }
  45.  
  46. /**
  47. * @param args the command line arguments
  48. */
  49. public static void main(String[] args) {
  50. Connection con = conectar();
  51.  
  52. for (int i = 0; i < 2; i++) {
  53. new Thread(){
  54. @Override
  55. public void run() {
  56. for(int i = 0; i < 300; i++){
  57. try {
  58. inserirItem(con, 5, seraQueVaiDemorar());
  59. } catch (Exception ex) {
  60. Logger.getLogger(Concorrencia.class.getName()).log(Level.SEVERE, null, ex);
  61. }
  62. }
  63. }
  64.  
  65. }.start();
  66. }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement