我需要创建2个运行相同SQL过程但具有不同参数的实例。
public void run() {
// TRUE if there is no more VER_STOCK
boolean booEsgotado = false;
System.out.println("Starting thread" + numThread );
try {
objLigacao = DriverManager.getConnection(LIGACAO,
UTILIZADOR, SENHA);
// manual control of transactions
objLigacao.setAutoCommit(false);
while (booEsgotado == false && i<=5) {
try {
objComando = objLigacao.prepareCall(INSERE);
// 1 = first parameter (:1)
objComando.setInt(1, ID);
objComando.setInt(2, PRODUTO);
objComando.setInt(3, Q);
objComando.execute();
objComando.close();
// If done with success commit the operations
objLigacao.commit();
i++;
System.out.println("Sold a unit in thread " + numThread + " i = " + i);
objComando = objLigacao.prepareCall(QUANT);
objComando.setInt(1, PRODUTO);
objResultado = objComando.executeQuery();
while(objResultado.next()) {
stock=objResultado.getInt(1);}
System.out.println("Stock atual=" + stock);
}
catch (SQLException objExcepcao) {
System.out.println("" + objExcepcao.getMessage());
// If something failed rollback the operations
objComando.close();
objLigacao.rollback();
booEsgotado = true;
System.out.println("Product is out of stock in thread" + numThread);
}
}
// Libertação de recursos.
objLigacao.close();
} catch (SQLException objExcepcao) {
System.out.println(objExcepcao.getMessage());
}
System.out.println("The end of thread " + numThread );
}
问题是我只能在两个实例中使用相同的参数运行相同的过程。我需要在两个实例中执行相同的过程但不同的参数。
runne1 objInstancia1 = new runne1(1);
runne1 objInstancia2 = new runne1(2);
// Create a thread for each instance
Thread objThread1 = new Thread(objInstancia1);
Thread objThread2 = new Thread(objInstancia2);
objThread1.start();
objThread2.start();
try {
objThread1.join();
objThread2.join();
答案 0 :(得分:0)
子类Thread
,用于提供指定所需参数的构造函数,并将它们存储为实例字段
这样,您就可以在run()
方法中使用它们。
public class MyCallThread extends Thread {
private int paramOne;
private int paramTwo;
public MyCallThread (Runnable runnable, int paramOne, int paramTwo){
super(runnable);
this.paramOne = paramOne;
this.paramTwo = paramTwo;
}
public void run(){
...
objComando.setInt(1, paramOne);
...
}
}
并将其实例化为:
int paramOne = ...;
int paramTwo = ...;
Thread objThread1 = new MyCallThread(objInstancia1, paramOne, paramTwo);
...