2016-12-29 5 views
2

URL에서 가격을 받고이를 정수로 파싱하는 데 사용할 수있는 "파서 (Parser)"클래스가 있습니다.생성자에서 URL을 동시에 구문 분석하는 방법은 무엇입니까?

그런 다음 이러한 변수를 사용하여 개체를 만드는 다른 클래스가 있습니다. 문제는 연속적으로 실행되기 때문에 매우 느립니다.

URL을 병렬로 구문 분석하려면 어떻게해야합니까?

public class Parser { 
    public static int getPrice(String url) { 
     String price = ""; 
     try { 
      Document doc = Jsoup.connect(url).get(); 
      price = doc.select("h3").select("span").attr("title"); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     return parseInt(price); 
    } 

    public static double parseDouble(String parseMe) { 
     NumberFormat ukFormat = NumberFormat.getNumberInstance(Locale.UK); 
     double parsed = 0; 
     try { 
      parsed = ukFormat.parse(parseMe).doubleValue(); 
     } catch (ParseException e) { 
      e.printStackTrace(); 
     } 
     return parsed; 
    } 
} 

//Here is an example of the class 
public class Example(){ 
    private int field1, field2; 

    public Example(String url1, String url2){ 
     field1=Parser.getPrice(url1); 
     field2=Parser.getPrice(url2); 
    } 
} 

답변

1

:

를 귀하의 경우 나는 당신의 코드가 같을 것이다하는 방식으로 CyclicBarrier 작업 제안
public Example(String url1, String url2) { 
    // Create executorService. 
    ExecutorService executorService = Executors.newWorkStealingPool(); 

    // Submit both tasks to executorService. 
    Future<Integer> future1 = executorService.submit(new Callable<Integer>() { 
     @Override 
     public Integer call() throws Exception { 
      return Parser.getPrice(url1); 
     } 
    }); 
    Future<Integer> future2 = executorService.submit(new Callable<Integer>() { 
     @Override 
     public Integer call() throws Exception { 
      return Parser.getPrice(url2); 
     } 
    }); 

    // Shutdown executorService. (It will no longer accept tasks, but will complete the ones in progress.) 
    executorService.shutdown(); 

    // Handle results of the tasks. 
    try { 
     // Note: get() will block until the task is complete 
     field1 = future1.get(); 
     field2 = future2.get(); 
    } catch (InterruptedException e) { 
     // TODO Handle it 
    } catch (ExecutionException e) { 
     // TODO Handle it 
    } 
} 
0

는 내가 같은 기능에있는 두 개의 URL을 구문 분석을했다했다 나를 위해, 정확히 같은 경우가 있고, 대신 정수를 반환하는 대신 두 정수의 배열을 반환하고,이었다 더 빨리. 당신과 같이, ExecutorService을 사용할 수 있습니다, 당신은 getPrice 호출이 비동기 적으로 실행하려는 경우

final CyclicBarrier cb = new CyclicBarrier(2); // the parameter 2 is the number of threads that will invode the await method 

    long startTime = System.nanoTime();// this is just the start time to measure how many it took 
    Thread t1 = new Thread(){ 
     public void run(){ 
      try { 
       cb.await(); 
       int field1 = Parser.getPrice(url1); 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } catch (BrokenBarrierException e) { 
       e.printStackTrace(); 
      } 

     }}; 

     Thread t2 = new Thread(){ 
      public void run(){ 
       try { 
        cb.await(); 
        int field2 = Parser.getPrice(url2); 
       } catch (InterruptedException e) { 
        e.printStackTrace(); 
       } catch (BrokenBarrierException e) { 

        e.printStackTrace(); 
       } 

      }}; 

      t1.start(); 
      t2.start(); 
    long endTime = System.nanoTime();// end time of execution 
    long duration = (endTime - startTime); 
    System.out.println(duration); 
관련 문제