Advertisement
Guest User

Untitled

a guest
Apr 28th, 2016
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.46 KB | None | 0 0
  1. /*
  2. * To change this license header, choose License Headers in Project Properties.
  3. * To change this template file, choose Tools | Templates
  4. * and open the template in the editor.
  5. */
  6. package concorrencia;
  7.  
  8. import java.sql.PreparedStatement;
  9. import java.sql.ResultSet;
  10. import java.sql.Connection;
  11. import java.sql.DriverManager;
  12. import java.sql.SQLException;
  13. import java.util.logging.Level;
  14. import java.util.logging.Logger;
  15.  
  16.  
  17.  
  18. /**
  19. *
  20. * @author Francisco
  21. */
  22. public class Concorrencia {
  23.  
  24.  
  25. private static Connection conectar(){
  26. try {
  27. Class.forName("com.mysql.jdbc.Driver");
  28. return DriverManager.getConnection("jdbc:mysql://localhost/fiscal", "jp", "");
  29. } catch (ClassNotFoundException ex) {
  30. Logger.getLogger(Concorrencia.class.getName()).log(Level.SEVERE, null, ex);
  31. } catch (SQLException ex) {
  32. Logger.getLogger(Concorrencia.class.getName()).log(Level.SEVERE, null, ex);
  33. }
  34. return null;
  35. }
  36.  
  37. private static int getProximoId(Connection con, int cupomId) throws SQLException{
  38. PreparedStatement stmt = con.prepareStatement("select max(nr_item) from item_cupom where cupom_id = ?");
  39. stmt.setInt(1, cupomId);
  40. ResultSet rs = stmt.executeQuery();
  41. try{
  42. if(rs.next()){
  43. return rs.getInt(1) + 1;
  44. }else{
  45. return 1;
  46. }
  47. }finally{
  48. rs.close();
  49. stmt.close();
  50. }
  51. }
  52.  
  53. public static void inserirItem(Connection con, int cupomId, boolean demorar) throws SQLException, InterruptedException{
  54. int nrItem = getProximoId(con, cupomId);
  55. if(demorar){
  56. Thread.sleep(200);
  57. }
  58. PreparedStatement pstmt = con.prepareStatement("insert into item_cupom(cupom_id, nr_item) values(?, ?);");
  59. pstmt.setInt(1, cupomId);
  60. pstmt.setInt(2, nrItem);
  61. pstmt.execute();
  62. pstmt.close();
  63. }
  64.  
  65. private static boolean seraQueVaiDemorar(){
  66. double valor = Math.random();
  67. return valor > 0.8;
  68. }
  69.  
  70. /**
  71. * @param args the command line arguments
  72. */
  73. public static void main(String[] args) {
  74. Connection con = conectar();
  75.  
  76. for (int i = 0; i < 2; i++) {
  77. new Thread(){
  78. @Override
  79. public void run() {
  80. for(int i = 0; i < 300; i++){
  81. try {
  82. inserirItem(con, 5, seraQueVaiDemorar());
  83. } catch (Exception ex) {
  84. Logger.getLogger(Concorrencia.class.getName()).log(Level.SEVERE, null, ex);
  85. }
  86. }
  87. }
  88.  
  89. }.start();
  90. }
  91. }
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement