在swingworker类中不适用于循环

时间:2014-02-25 10:52:18

标签: java swing http swingworker

也许我做错了。但我无法解决这个问题。 Swing Worker类中的for循环不起作用。

public class _5Strategy_A extends SwingWorker<Integer, Integer> {

_4HttpRequest_Naver attk = new _4HttpRequest_Naver();

int num_acc;
int time ;
int total_post;
int total_comment;
int init = 0;
int execute = 0;
int i = 0;
int c = 0; 
static int k = 0;
static int response = 0;        
private boolean _suspended = false;

public synchronized void suspend() { _suspended = true; notify(); }
public synchronized void resume() { _suspended = false; notify(); }

  @Override
protected Integer doInBackground() throws Exception {

  init = 0;
  publish(new Integer[] { init }); //
  _1SetProxy.setProxy();

  init = 1;
  publish(new Integer[] { init });  // 
  _3SetTarget_NaverPopular25.setTarget_Naver();
  _3SetTarget_NaverRise50.setTarget_NaverUp50();
  new _3SetTarget_NaverRise50(10);

// ***************************************************************** //  
// ***************************************************************** //  
  for (int ch=0; ch<5; ch++){
        System.out.println("Obviously This statement could be shown 5 times.")
 // ***************************************************************** //  

  for (k=0; k<2; k++){

       synchronized(this) {
              while (_suspended == true) {
                  wait(); // The current thread will block until some else calls notify()
                  // Then if _suspended is false, it keeps looping the for
              }
          }

  init = 2;
  publish(new Integer[] { init });

    String page = attk.GetLoginPage_Naver(_0Storing.url);
    String raw = String.valueOf(_9AccountsManager.tableNaverAccounts_A.getModel().getValueAt(0, num_acc));
    String[] raw_splited = raw.split(":");
    String id = raw_splited[0];
    String pw = raw_splited[1];
    String postParams = attk.getFormParams(page, id, pw);
    CookieHandler.setDefault(new CookieManager());

  init = 3;
  publish(new Integer[] { init }); 

    // POST 
    attk.loginNaver(_0Storing.url, postParams);
    response = 0; // Initializing response code.

  init = 4;
  publish(new Integer[] { init });

         // POST
        try {
            attk.AttackNaver(_0Storing.baseURL, String.valueOf(GUI.proxyTable.getModel().getValueAt(k%17, 0)), Integer.parseInt(String.valueOf(GUI.proxyTable.getModel().getValueAt(k%17, 1))), _3SetTarget_NaverPopular25.attkParam[k%34]);
            } catch (Exception e) {
                }

    System.out.println(+k+" looping.");
   }

   num_acc++; 
   k=0;
   init=1;


  }


  // ***************************************************************** //
  // ***************************************************************** //  

  return null;
  } // End of doInBackground()

  protected void process(List<Integer> chunks) {

  /* Initialization */
    if(init==0){

        _0Storing.addRow("GET", "Checking", _1SetProxy.proxy_url, "LOCAL");

    }

    if(init==1){

        _0Storing.setRst("OK");
        _0Storing.addRow("GET", "Targetting", "http://finance.naver.com/sise/lastsearch2.nhn", "LOCAL"); 

    }     

    if(init==2){

        _0Storing.setRst("OK");
        _0Storing.addRow("GET", "Extracting", _0Storing.url, "LOCAL"); 

    }

    if(init==3){

        _0Storing.setRst("OK");
        _0Storing.addRow("POST", "Login...("+_9AccountsManager.tableNaverAccounts_A.getModel().getValueAt(0, num_acc)+")", _0Storing.url, "LOCAL"); 

      }

    if(init==4){

        _0Storing.setRst("OK");

        try {
        _0Storing.addRow("POST", _3SetTarget_NaverPopular25.text[k%24], _3SetTarget_NaverPopular25.code[k%24], String.valueOf(GUI.proxyTable.getModel().getValueAt(k%17, 0)));      
        } catch (ArrayIndexOutOfBoundsException e){
        }

    }

    }

  @Override
  protected void done() {
    if (isCancelled())
      _0Storing.addLog("\nCancelled !");
    else{
        GUI.bottomStatus.setText("Finish !");
        if (response == 0)
        GUI.mainTable.setValueAt("OK", GUI.mainTable.getRowCount()-1, 5);
        else
        GUI.mainTable.setValueAt("FAILED", GUI.mainTable.getRowCount()-1, 5);
    }
   }

}

上面的代码是我的代码。对不起脏和复杂。但我无法总结它,因为我不知道这个问题的原因是什么。请专注于// * // for循环。也许我的陈述可以在控制台中显示5次。但我只能看到一次。请告诉我为什么这个for循环不起作用。谢谢。

2 个答案:

答案 0 :(得分:1)

以下两个块都在同一个对象synchronizedthis

public synchronized void resume() { _suspended = false; notify(); }

synchronized(this) {
    while (_suspended == true) {
        wait(); // The current thread will block until some else calls notify()
        // Then if _suspended is false, it keeps looping the for
    }
}

所以你有一个僵局。当SwingWorker处于resume()状态时,您永远无法wait()因为同步不允许它。有关同步的更多信息,我建议您查看Oracle tutorial,特别是Intrinsic Locks

部分

另一方面,我清洗了你打算用这个代码做的任何邪恶。它确实让我感到很奇怪attk = new _4HttpRequest_Naver();

答案 1 :(得分:0)

这是一个品味问题,但我实际上并不喜欢这里管理并发的方式。我建议你消除所有的循环,wait()等,然后让你的SwingWorker阻塞自己进入BlockingQueue读取。类似的东西:

public static BlockingQueue<WorkerCommand> queue =
   new ArrayBlockingQueue<WorkerCommand>();

// WorkerCommand is a simple bean with a getter and a setter for the command

// ....

boolean keepOn = true;
while (keepOn) { 
   WorkerCommand command = queue.poll(); // blocking!
   if (command.getCommand().equals(COMMAND_STOP)) { keepOn = false; }
   else {
       // whatever you need
   }
}

// Clients just put commands into the queue, which makes the worker to wake up, consume and
//   serve the command

通过这种方式,您可以使用高级Java工具管理并发性,并可以专注于执行任务。这样,如果你在某个时刻需要更多的工人,它就会轻易升级。