2012-11-21 3 views
0

멀티 쓰레드 및 벡터를 사용하여 대화방 서버를 만드는 중입니다. 모든 신규 사용자는 닉네임을 제공하고 벡터에 닉네임을 저장했습니다. 하지만 현재 스레드에 대한 벡터 요소를 검색하는 방법을 모르겠습니다. 이 방법 울부 짖는 소리가 벡터의현재 스레드의 벡터 요소를 검색하는 방법은 무엇입니까? 대화방 서버

userName = input.nextLine(); // the user enters their name 

usersList.add(userName);  //add it to the vector of users 

String word = usersList.elementAt(????); //how do i retrieve this current username? 

output.println(word + " has joined the conversation.");  
+0

이 권리를 갖게하십시오 : 멀티 스레드 채팅 서버가 있습니다. 각 연결은 스레드 (또는 실행 가능)를 얻고, 공유 사용자 목록 (아마도'ArrayList'?)을가집니다. 나는 정확하게 이해 했는가? – didierc

답변

0

내부 synchrozation이 당신의 작업에 대한 충분하지 않습니다 스레드에, 나는 다음과 같은

Vector<String> userList = new Vector<String>(); 

synchronized void addUser(String userName) { 
    userList.add(userName); 
    String word = userList.elementAt(userList.size() - 1); 
    System.out.println(word + " has joined the conversation.");  
} 

지금 당신이 ArrayList의 벡터를 대체 할 수 있습니다 제안합니다.

0

전체 메서드를 동기화하려는 경우 다음과 같이 교착 상태가 발생할 수 있습니다. methodA1의 메서드 호출에 대해 클래스 A는 해당 개체에 대한 잠금을 가져온 다음 클래스 B 개체의 methodB2()를 호출하기로 결정하고 ClassB를 잠급니다. 그러나 클래스 B의 개체에서 진행중인 메서드 호출 메서드 B1()이있는 경우 ClassA의 잠금을 얻기 위해 ClassB의 잠금을 얻고 ClassB의 잠금을 가져 오는 ClassA의 노력이 실패하고 교착 상태가 발생합니다.

class ClassA { 
    public synchronized void methodA1(ClassB classB) { 
     classB.methodB2(); 
    } 
    public synchronized void methodA2() { } 
} 

class ClassB { 
    public synchronized void methodB1(ClassA classA) { 
     classA.methodA2(); 
    } 
    public synchronized void methodB2() { } 
} 

개인 최종 잠금 객체를 사용하면 협력 객체간에 교착 상태가 발생하지 않도록 할 수 있습니다.

private final Object lock = new Object(); 
void addUser(String userName) { 
    synchronized(lock){ 
     // method body. Add user to list 
    } // lock is released. now any cooperating object can use 'lock'. 

    // addUser can obtain a lock on any cooperating object. 
} 
관련 문제