import java.sql.*; import java.util.*; class Tmp extends Thread { private int newId() { Connection c = null; int result = 10000; try { c = DriverManager.getConnection( "jdbc:mysql://localhost/test", "root","password"); Statement stmt = c.createStatement(); stmt.executeUpdate("LOCK TABLES keynum WRITE"); stmt.close(); PreparedStatement pstmt = c.prepareStatement( "SELECT keyid FROM keynum"); ResultSet rs = pstmt.executeQuery(); rs.next(); result = rs.getInt("keyid"); result++; rs.close(); PreparedStatement pstmt2 = c.prepareStatement( "UPDATE keynum SET keyid=?"); pstmt2.setInt(1, result); pstmt2.executeUpdate(); pstmt2.close(); } catch(Exception e) { System.out.println(e.toString()); System.exit(1); } finally { try { try { if (c != null) { Statement stmt = c.createStatement(); stmt.executeUpdate("UNLOCK TABLES"); stmt.close(); } } catch(SQLException e) { System.out.println(e.toString()); } } finally { close(c); } } return result; } private void close(Connection c) { if (c != null) { try { if (!c.isClosed()) { c.close(); } } catch(SQLException e) { System.out.println(e.toString()); } } } public void run() { while(true) { System.out.println("New id: "+newId()); } } } public class mysql { static { try { Class.forName("com.mysql.jdbc.Driver"); } catch(Exception e) { System.out.println(e); System.exit(1); } } public static void main(String[] args) throws Exception { List tmp = new ArrayList(); for(int i = 0 ; i < 10 ; i++) { tmp.add(new Tmp()); } Iterator i = tmp.iterator(); while(i.hasNext()) { Thread t = (Thread)i.next(); t.start(); } i = tmp.iterator(); while(i.hasNext()) { Thread t = (Thread)i.next(); t.join(); } } }