0
如何在java中使用相同的程序发送和接收数据?更糟糕的是,我需要在同一时间同时进行这两项操作。如何使相同的程序像服务器和客户端一样工作(使用java中的套接字)
如何在java中使用相同的程序发送和接收数据?更糟糕的是,我需要在同一时间同时进行这两项操作。如何使相同的程序像服务器和客户端一样工作(使用java中的套接字)
您需要一个行为良好的队列,例如两个Thread
之间的BlockingQueue
。
public class TwoThreads {
static final String FINISHED = "Finished";
public static void main(String[] args) throws InterruptedException {
// The queue
final BlockingQueue<String> q = new ArrayBlockingQueue<String>(10);
// The sending thread.
new Thread() {
@Override
public void run() {
String message = "Now is the time for all good men to come to he aid of the party.";
try {
// Send each word.
for (String word : message.split(" ")) {
q.put(word);
}
// Then the terminator.
q.put(FINISHED);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
{ start();}
};
// The receiving thread.
new Thread() {
@Override
public void run() {
try {
String word;
// Read each word until finished is detected.
while ((word = q.take()) != FINISHED) {
System.out.println(word);
}
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
{ start();}
};
}
}
您使用的标签表明您明白您需要使用多个线程;除此之外,没有特别的技巧。你有没有需要帮助的具体问题? – 2012-03-03 21:40:40
是的,将发送和接收部分放在单独的线程中(并且进一步使服务部分多线程以便为多个客户端服务)工作?这是处理这种情况的正常方式吗? – Chani 2012-03-03 21:44:36
@ return0请不要忘记,在JVM中,不会保证不间断的线程生命周期。他们总是有可能被暂停,取消优先,重新开始等等。这会在某些时候破坏一些东西。 – 2012-03-03 21:52:38