被分配唯一的ID,我需要插入其中有两个columns-每个线程应该同时插入
ID Primary Key String
Data String
数据库因此,这意味着ID应该是唯一的每一次,否则会抛出一个异常duplicate row in unique index
插入时。我需要在这个范围内1-100000
之间做出选择ID因此,这意味着每个线程应该使用唯一的ID始终在线
下面是多线程程序我写了,将后每次插入到数据库不同的独特的ID从ArrayBlockingQueue
获得。
所以这个程序将是线程安全或不是?或者还有没有其他更好的方法来获得每个线程每次唯一的ID?或者下面的程序可能会导致duplicate row in unique index
?
private static LinkedList<Integer> availableExistingIds = new LinkedList<Integer>();
public static void main(String[] args) {
for (int i = 1; i <= 100000; i++) {
availableExistingIds.add(i);
}
BlockingQueue<Integer> pool = new ArrayBlockingQueue<Integer>(200000, false, availableExistingIds);
ExecutorService service = Executors.newFixedThreadPool(10);
for (int i = 0; i < noOfTasks * noOfThreads; i++) {
service.submit(new ThreadTask(pool));
}
}
class ThreadTask implements Runnable {
private BlockingQueue<Integer> pool;
private int id;
public ThreadTask(BlockingQueue<Integer> pool) {
this.pool = pool;
}
@Override
public void run() {
try {
dbConnection = getDBConnection();
preparedStatement = dbConnection.prepareStatement(INSERT_SQL);
id = pool.take();
preparedStatement.setString(1, String.valueOf(id));
preparedStatement.setString(2, ACCOUNT);
preparedStatement.executeUpdate();
} finally {
pool.offer(id);
}
}
}
哪个数据库?你不能使用“身份”类型吗? –
我正在使用一个名为XpressMP的新数据库。你能否以身份解释我是什么意思? – AKIWEB