Java 如何检索当前线程的向量元素?聊天室服务器
我正在使用多线程和向量创建聊天室服务器。每个新用户都会给出他们的昵称,我将昵称存储在一个向量中。但我不知道如何检索当前线程的向量元素。下面的方法在线程中Java 如何检索当前线程的向量元素?聊天室服务器,java,multithreading,vector,chatroom,Java,Multithreading,Vector,Chatroom,我正在使用多线程和向量创建聊天室服务器。每个新用户都会给出他们的昵称,我将昵称存储在一个向量中。但我不知道如何检索当前线程的向量元素。下面的方法在线程中 userName = input.nextLine(); // the user enters their name usersList.add(userName); //add it to the vector of users String word = usersList.elementAt(????); //how do
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.");
向量的内部同步不足以完成您的任务,我建议如下
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 userList=new Vector();
同步的void addUser(字符串用户名){
userList.add(用户名);
String word=userList.elementAt(userList.size()-1);
System.out.println(word+“已加入对话”);
}
现在您可以用ArrayList替换Vector。如果您决定同步整个方法,您可能会遇到以下死锁: 对于methodA1的方法调用,类A在其对象上获得锁,然后决定在类B对象上调用methodB2(),并尝试在类B上获得锁。但如果 在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.
}
让我弄清楚:您有一个多线程聊天服务器。每个连接都有一个线程(或一个可运行线程),并且您有一个共享的用户列表(一个
ArrayList
可能?)。我理解对了吗?