如何使同一程序像服务器和客户机一样工作(使用java中的套接字)
如何在java中从同一程序发送和接收数据?更糟糕的是,我需要同时并行执行这两项操作。您需要一个性能良好的队列,例如两个如何使同一程序像服务器和客户机一样工作(使用java中的套接字),java,multithreading,sockets,Java,Multithreading,Sockets,如何在java中从同一程序发送和接收数据?更糟糕的是,我需要同时并行执行这两项操作。您需要一个性能良好的队列,例如两个线程之间的阻塞队列 public class TwoThreads { static final String FINISHED = "Finished"; public static void main(String[] args) throws InterruptedException { // The queue final BlockingQueu
线程之间的阻塞队列
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();}
};
}
}
公共类双线程{
静态最终字符串FINISHED=“FINISHED”;
公共静态void main(字符串[]args)引发InterruptedException{
//排队
最终阻塞队列q=新阵列阻塞队列(10);
//发送线程。
新线程(){
@凌驾
公开募捐{
String message=“现在是所有好人都来帮助党的时候了。”;
试一试{
//发送每个单词。
for(字符串字:message.split(“”){
q、 放(字);
}
//然后是终结者。
q、 放置(完成);
}捕获(中断异常例外){
Thread.currentThread().interrupt();
}
}
{start();}
};
//接收线程。
新线程(){
@凌驾
公开募捐{
试一试{
字符串字;
//阅读每个单词,直到检测到已完成。
while((word=q.take())!=FINISHED){
System.out.println(word);
}
}捕获(中断异常例外){
Thread.currentThread().interrupt();
}
}
{start();}
};
}
}
您使用的标记表明您了解需要使用多个线程;除此之外,没有特殊的技巧。您是否有需要帮助的特定问题?是的,将发送和接收部分放在单独的线程中(并进一步使服务部分多线程化,以便能够为多个客户端提供服务)是否有效?这是处理这种情况的正常方法吗?@return0请不要忘记,在JVM中,永远不能保证线程生命周期不中断。它们总是有被挂起、取消优先级、恢复等的可能性。这会在某个时候破坏某些东西。@如果可以,那么你建议我研究什么?只要确保你不使用相同的资源,而不在不同的线程中保护它们,不同的线程不依赖于另一个线程执行的操作,而不检查另一个线程是否真的完成了。你会没事的