Java 使用线程创建套接字数组
我是Java新手,试图理解套接字和线程。我创建了一个迷你聊天程序,但它使用:Java 使用线程创建套接字数组,java,multithreading,sockets,Java,Multithreading,Sockets,我是Java新手,试图理解套接字和线程。我创建了一个迷你聊天程序,但它使用: private static Socket clientSocket = null; private static final socketThread[] threads = new socketThread[maxClientsCount]; 然后使用以下方法创建线程: //code clientSocket = serverSocket.accept(); //code for (i = 0; i < m
private static Socket clientSocket = null;
private static final socketThread[] threads = new socketThread[maxClientsCount];
然后使用以下方法创建线程:
//code
clientSocket = serverSocket.accept();
//code
for (i = 0; i < maxClientsCount; i++) {
// If found create thread
if (threads[i] == null) {
(threads[i] = new socketThread(clientSocket, threads)).start();
break;
}
}
// if no available sockets available, say "too busy" and close
然后处理所有数据并将其传递给chatprotocol类,该类处理如何解释每个连接的输入以及如何为每个连接提供输出
这允许我使用以下方式访问每个插座:
threads[i].chatproto.[insert method/variable]
访问每个套接字处理程序
我一直在阅读,也许我应该使用“implements runnable”,但在转换代码时遇到了问题。在本例中使用“implements runnable”是否正确?如果这样,如何访问chatprotocol类的每个实例
谢谢。一般来说,使用“Implements runnable”是启动新线程的最佳方式。但是这种交互的思想与您的实现不同,因此显然很难转换代码。这样做的目的是从实际线程封装代码,以便您能够在其他线程中重新运行它。问题是,您没有访问可运行类的权限。
一种解决方案是将socketThread的每个实例注入其自己的chatproto对象。这看起来像是
正如用户3297516所指出的,“implements runnable”始终是启动线程的最佳方式。但由于它是一个接口,您无法正常创建它的实例。要创建实例,必须创建匿名内部类。例如:
class InnerRunnable2 {
private int countDown = 5;
private Thread t;
public InnerRunnable2(String name) {
t = new Thread(new Runnable() {
public void run() {
while (true) {
System.out.println(this);
if (--countDown == 0)
return;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
public String toString() {
return Thread.currentThread().getName() + ": " + countDown;
}
}, name);
t.start();
}
}
class socketThread implements Runnable {
//code
chatproto = null;
public static socketThead (chatprotocol chatproto) {
this.chatproto = chatproto;
}
// code
}
class InnerRunnable2 {
private int countDown = 5;
private Thread t;
public InnerRunnable2(String name) {
t = new Thread(new Runnable() {
public void run() {
while (true) {
System.out.println(this);
if (--countDown == 0)
return;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
public String toString() {
return Thread.currentThread().getName() + ": " + countDown;
}
}, name);
t.start();