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.");    
4

2 回答 2

0

Vector的内部同步不足以完成您的任务,我建议以下

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.");    
}

现在您可以将 Vector 替换为 ArrayList。

于 2012-11-21T03:21:01.513 回答
0

如果您决定同步整个方法,您可能会以这种方式遇到死锁: 对于 methodA1 的方法调用,A 类获取其对象上的锁,然后决定在 B 类对象上调用 methodB2() 并尝试获取 ClassB 上的锁. 但是,如果 ClassB 的对象中有一个方法调用 methodB1() 正在进行中,ClassA 获取 B 的锁的努力以及 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() {   }
}   

我建议你使用一个私有的 final Lock 对象,它可以避免你遇到合作对象之间的死锁。

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.
}
于 2012-11-21T07:19:32.533 回答