Java中父线程和子线程之间的通信 [英] Communication between parent and child thread in Java

查看:779
本文介绍了Java中父线程和子线程之间的通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个主线程,并在该线程中启动了一个新线程. (子线程).该子线程将打开服务器套接字,并开始侦听连接. 我希望该线程停止执行,并在主线程从外部获取消息(不关心消息的位置)时关闭它已初始化的所有内容(如Socket).我要如何停止线程并关闭所有连接.

I have got a main thread and within that thread I start a new thread. (the child thread). That child thread opens a server socket and starts listening for a connection. I want that thread to stop its execution and close whatever it has initialized (like the Socket) when the main thread gets a message from outside (from where it gets the the message is not the concern). How should I stop the thread and close all the connections is what I want.

我应该使用共享变量吗?这样,当主线程收到消息时,它应该对其进行修改,而子线程应该继续检查该共享变量中的更改?

Should I use a shared variable? so that when the main thread receives the message it should modify it and the child thread should continually check for the changes in that shared variable?

我应该如何实施?一些有用的链接可能会有所帮助或示例代码?

How should I implement it? Some useful links may help or a sample code ?

我尝试过的方法如下: 在主线程中,我声明了一个变量

What I have tried is as follows: in the main thread I have declared a variable

 flag=0;

当主线程收到消息时,它会设置

when the main thread receives the message, it sets

flag = 1 ;

并且线程监听更改,如下所示:

and the thread listens for the change as follows:

  void ()run{

       while(true){

            if(flag==1){
                   break;
              }

       sock1 = Ssocket.accept(); 
  }

但是上面的代码根本不起作用.我该怎么办?

But the above code is not at all working. How should I do it?

推荐答案

中断线程的正确方法是通过中断机制.在主线程中,当您要停止子线程时,请调用:

The proper way to interrupt a thread is via the interruption mechanism. In your main thread, when you want to stop the child thread, you call:

childTread.interrupt();

在子线程中,您可以执行以下操作:

and in the child thread, you do something like:

public void run() {
    try {
        while (!Thread.currentThread.isInterrupted) {
            sock1 = Ssocket.accept();
            //rest of the code here
        }
    } catch (InterruptedException e) {
        Thread.currentThread.interrupt(); //good practice
    }
    //cleanup code here: close sockets etc.
}

请注意,Ssocket.accept不可中断,因此,如果要使其停止等待,则必须从外部关闭它,以迫使它抛出IOException.

Note that Ssocket.accept isn't interruptible, so if you want to stop it from waiting, you will have to close it from outside, to force it to throw an IOException.

这篇关于Java中父线程和子线程之间的通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆