2012-03-05 2 views
0

나는 2 개의 클래스를 가지고 있습니다. 다른 고객은 TestThreadPool으로 전화를 걸어 TestThreadExecutor을 호출하여 ExecutorService에 액세스합니다. 문제는 항상 TestThreadExecutor을 생성하므로 ThreadPool은 시작되지 않습니다.static ExecutorService

따라서 threadPool을 시작하는 정적 방법으로 executeThreadExecutor을 설정하고 싶습니다. 정적 메서드와 정적 인 문제가 있습니까 ExecutorService?

싱글 톤과 같은 다른 대체 방법이 있습니까?


public class Client { 
    ... 
    TestThreadPool testThreadPool = new TestThreadPool(); 
    ... 
} 

public class TestThreadPool { 
    public void executeThread() { 
    TestThreadExecutor test = new TestThreadExecutor(); 
    ... 
    } 
} 

public class TestThreadExecutor { 
    public static ExecutorService testService = null; 

    public static void executeThreadExecutor { 
    if (testService == null) {  
     testService = Executors.newFixedThreadPool(15); 
    } 
    ... 
    } 
} 

답변

0

당신의 접근 방식은 좋아 보인다, 당신은 클래스의 방법을 통해 관리되기 때문에 내가는 ExecutorService을 공개 할 이유가 표시되지 않지만 그것으로 아무 문제가 없다,하는 캡슐화에 더 좋습니다. 물론 TestThreadExecutor을 싱글 톤으로 구현할 수 있습니다.

public class TestThreadExecutor { 
    private ExecutorService testService = Executors.newFixedThreadPool(15); 
    private static TestThreadExecutor instance = new TestThreadExecutor(); 

    private TestThreadExecutor() { 
    } 

    public static TestThreadExecutor getInstance() { 
     return instance; 
    }   
} 
+1

왜 생성자에서 testService를 설정하겠습니까? 왜 직접 설정하지 않았습니까? 클래스 생성자에서 정적 변수를 설정하는 것은 혼란 스럽습니다. – jtahlborn

+0

@jtahlborn : 나는 그것에 대해 생각하기에, 약간 혼란 스럽다. – Tudor

+0

감사합니다. 이것은 나를 위해 매우 도움이됩니다. executorService.shutdown()을 넣고 싶습니다. 내가 어디에서 가져야하니? catch 블록에 있습니까? 마침내 그것을 넣으려고했는데 새로운 일을 받아들이지 않습니다. – user12121