2017-12-07 10 views
-2

특정 값을 포함하는 (String, String) 유형의 문자열 또는 Hastable 목록입니다. 여러 스레드가 실행중인 상황에서 각 스레드가 위에서 언급 한 목록의 값 중 하나만 사용하도록합니다.목록에 잠금 생성 <String> 또는 Hastable <String, String>

예 : 목록 - Set1과, Set2를, SET3

Thread1이 Set1과를 사용하여 목록에있는 값 중 하나를 사용하려고 thread2 경우는, 그것은 가능한로만 Set2를하고 SET3을 얻어야한다. Thread1이 완료되면 Set1을 사용할 수 있어야합니다.

+2

그래서 지금까지 무엇을 시도 했습니까? – daniu

+0

차단 대기열을 사용할 수 있습니다. "BlockingQueue 구현은 스레드로부터 안전합니다." –

답변

0

당신이 시작하기 전에 적절한 Set를 추가 /를 List에 고정 및 제거하여 구현할 수/작업 마무리 후 : 당신이 제네릭을 사용할 수 물론

public class ListLock { 
    private List<Set<String>> list = new ArrayList<>(); 

    //initialize with some values 
    public ListLock(List<Set<String>> availableValues) { 
     this.list = availableValues; 
    } 

    //this will allow your Thread to get an available value. Your Thread needs to keep the selected value until the job is done and put it back 
    public void synchronized aquireValue(Selector selector) { 
     //this one is little bit tricky, you provide some interface, that has 1 method, that will call a "select" function on your Thread. 
     Set<String> selected = selector.select(list); 
     this.list.remove(selected); 
    } 

    //after job is done, put the value back in the list, so it's available for another Thread 
    public void synchronized releaseValue(Set<String> value) { 
     this.list.add(value); 
    } 
} 

이 클래스는 일반적인 만들기를