开发者

Android Thread problem

开发者 https://www.devze.com 2023-02-08 06:53 出处:网络
I开发者_JS百科 already know how to stop thread but my present scenario is somewhat different, I am listening for data from server in thread

I开发者_JS百科 already know how to stop thread but my present scenario is somewhat different, I am listening for data from server in thread

while (connected) 
{
    byte[] buffer = new byte[1024];
    if(in.read(buffer) > 0)// waits on this line
    {
        //do something  
    }
 }

now the problem is that although I set connected = false; then also it not stopping because it waits on in.read so , I also tried to Thread.interrupt but no luck


You should probably switch to using a SelectableChannel approach to reading/writing to sockets where non-blocking I/O is used and you can manage multiple connections by listening for 'events'. You then avoid being blocked in calls like read().

This, unfortunetly, is a fundamentally different model to the one you are currently using, so the switch over won't be quick or easy, but it will be worth the effort.

Check out these resources:

http://developer.android.com/reference/java/nio/channels/SocketChannel.html http://www.exampledepot.com/egs/java.nio/NbClientSocket.html


We need a little more info here:

  1. How do you declare and modify connected?
  2. Do you have a try-catch that is "eating" the InterruptedException?
  3. How do you create the thread?
  4. How are you starting the thread?
  5. How do you (attempt to) terminate the thread?
  6. Provide a sscce compliant example which we can copy & paste, compile and see your exact problem.

In general your code should look like this:

while (connected) 
{
    try
    {
        byte[] buffer = new byte[1024];
        if(in.read(buffer) > 0)// waits on this line
        {
            //do something  
        }
    }
    catch(InterruptedException ie)
    {
        // there are several ways which you can exit the loop:

        // 1. you can break
        // 2. set the connected flag to false

    }
}

Verify that you are actually catching the interrupt exception! If you're not catching it, then built a small sscce compliant example in which you're only reproducing the specific issue (should be pretty easy to do).


I modified the code in following way

while (connected) 
{
   byte[] buffer = new byte[1024];
   if(in.available()  > 0)// changed this line
   {
      in.read(buffer)
      //do something  
   }  
}

and it worked fine for me since in.available() statement is non- blocking I suppose

0

精彩评论

暂无评论...
验证码 换一张
取 消