0

我有以下内容,当我有大量数据时,它需要一些时间(提交),因此我认为可能为负责持久线程的方法创建,因为 IM 是线程的新手 1.我应该如何传递参数就像线程的 createClassInstance 一样。? 2.我应该如何将main里面的调用改为theard?

谢谢,

main之前的代码

public static void main(String[] args) throws Exception {

// Get class members
ClassHandle classMetaData = new ClassHandle();
createClassInstance = classMetaData.createClsObj(listClsObj);

// Persist data using JPA
PersistClassObject.persistObjects(createClassInstance,
        persistenceUnitName);

...

现在我实现了runnable并且我的参数有错误,我现在该怎么办

public class TheredTest implements Runnable {

    @Override
    public void run() {


        // Persist data using JPA
        PersistClassObject.persistObjects(createClassInstance,
                persistenceUnitName);



    }

}

解决方案后的代码

        ClassHandle classMetaData = new ClassHandle();
        createClassInstance = classMetaData.createClsObj(listClsObj);

        PersistRunnable persistRunnable = new PersistRunnable(createClassInstance, persistenceUnitName);

        Thread thread = new Thread(persistRunnable);
        thread.start();




------


    @Override
    public void run() {
        // your persistence code referring to those arguments

        // Persist data using JPA
        PersistClassObject.persistObjects(theObjectsToPersist,
                persistenceUnitName);
    }
4

1 回答 1

1

由于 PersistClassObject.persistObjects 是static,因此没有很好的方法将其设为 aRunnable并传入任何参数。Runnable(and ) 的一个缺点Callable是它们不接受参数。您每次都需要创建一些实例。例如非常粗略的东西,例如:

class PersistRunnable implements Runnable {
  final List theObjectsToPersist;
  final String persistenceUnitName;

  public PersistRunnable (List objectsToPersist, String persistenceUnitName) {
      this.theObjectsToPersist = objectsToPersist;
      this.persistenceUnitName = persistenceUnitName;
   }

   @Override
   public void run() {
       // your persistence code referring to those arguments
   }
}

这个新类是替换你的 PersistClassObject 还是补充它取决于你在哪里使用 PersistClassObject。

于 2013-04-26T16:13:10.513 回答