2014-05-23 1 views
0

그래, 모든 메소드가 스레드에서 실행되어야하는 Java 클래스가 있습니다. 하나의 스레드 만 시간과 특정 시간에 실행됩니다. Thread를 확장하는 내부 클래스로 이와 같이 구현했습니다.스레드 대기열을 가져 오는 데 걸리는 시간을 수정하십시오.

private void fetchTasks() { 
    new Thread() { 
     @Override 
     public void run() { 
      while(true) { 
       if(currentOperation == null && !operationList.isEmpty()) { 
        currentOperation = getOperation(); 
        while(currentOperation.scheduledStartTime > System.currentTimeMillis()) { 
         // do nothing, wait for proper time; 
        } 
        currentOperation.start(); 
       } 
      } 
     } 

    }.start(); 
} 
    private MyOperation getOperation() { 
    synchronized (operationList) { 
     return operationList.remove(); 
    } 
} 

내가 큐에 스레드를 추가 해요 : 다음

private class MyOperation extends Thread { 

    public static final String M1 = "method1"; 
    public static final String M2 = "method2"; 
    public static final String M3 = "method3"; 

    protected long scheduledStartTime = 0; 
    private String type; 

    public MyOperation(String type, long milliSecondsToWait) { 
     this.type = type; 
     scheduledStartTime = System.currentTimeMillis() + mlliSecondsToWait; 
    } 
    @Override 
    public void run() { 
     switch(type){ 
     case M1: 
      doMethod1(); 
      break; 
     case M2: 
      doMethod3(); 
      break; 
     case M3: 
      doMethod3(); 
      break; 

     } 
     setCurrentOperation(null); 
    } 
} 



private void setCurrentOperation(MyOperation task) { 
     synchronized (currentOperation) { 
      this.currentOperation = task; 
     } 
    } 

나는 스레드 큐 현재 실행중인 스레드 같은

private MyOperation currentOperation; 
private Queue <MyOperation> operationList; 

내가 가져 오는거야 작업이 예를 들면 다음과 같습니다.

addOperation(new MyOperation(M1, 5)); 

    private void addOperation(MyOperation task) { 
    synchronized (operationList) { 
     operationList.add(task); 
    } 
} 

내 질문 :

다른 스레드에서 각 메소드를 실행하는 더 좋은 방법이 있습니까?

스레드 큐를 올바르게 가져 오는 방법이 맞습니까?

당신에게 그냥 작은 일을

+0

switch 문은 다형성에 대한 절박한 외침과 같습니다. 생성자에 'type'인수를 허용하는 하나의 MyOperation 클래스 대신 공통 인터페이스를 구현하거나 공통 추상 클래스에서 상속하는 세 가지 다른 MyOperationXxxxxx 클래스를 사용하는 것이 좋습니다. 즉, Java 유형을 사용하여 응용 프로그램의 '유형'개념을 표현하는 것이 어떻습니까? –

+0

그래, 나는 이것이 일종의 추악한 데 동의한다. 기본적으로 클래스의 모든 메소드가 다른 스레드에서 실행되도록하기 때문에이 작업을 수행했습니다. 또한 "setCurrentOperation (null)"때문에 run() 메서드의 끝에서 호출해야합니다 – Manza

답변

0

대단히 감사 : 당신의 operationsList이 비어 있거나 currentOperation이 스레드는 정말 빨리 빙빙 돌고 시작 null가 아닌 경우. 이것을 피하려면 Thread.wait().notify()을 사용할 수 있습니다.

또한 synchronized의 유무에 관계없이 currentOperation을 사용하고 있습니다. 이것은 당신을 곤경에 빠지게 할 수 있습니다.

0

ScheduledExecutorService (java.util.concurrent)를 사용하여 작업을 예약 했습니까?

관련 문제