简体   繁体   中英

How to wait for thread to finished in android?

How to wait for thread to finish for starting new thread which is dependent on previous thread in android??

Consider that I have 2 thread thread1 and thread2. In thread1 I performed writing task on socket and in thread2 I perforem reading task of socket. After writing on socket I have to wait for sometime as the client need to process the data and respond back after that reading process will be initiate. So how to ensure that writing on the socket is complete and reading from socket is complete.

here is the thread code im using,

class Thread1 implements Runnable {

    @Override
    public void run() {

        try {
            socket = new Socket(SERVER_IP, SERVER_PORT);
            output =  socket.getOutputStream();
            input = socket.getInputStream();

            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    //tvMessage.setText("Connected\n");
                    Toast.makeText(MainActivity.this, "Connected", Toast.LENGTH_LONG).show();
                }
            });
        } catch (UnknownHostException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class Write_Thread implements Runnable {

    @Override
    public void run() {
        try {
            output.write(output_array,0,data_length);
        } catch (UnknownHostException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

class Read_Thread implements Runnable {
    @Override
    public void run() {
        while (true) {
            try {
                rec_count = input.read(input_array);
            } catch (UnknownHostException e1) {
                e1.printStackTrace();
            }catch (IOException e) {
                e.printStackTrace();
            }

        }

    }
}

I am calling those read and write threads in the onclick listener of the button.

you can read about join(). or you can make a callback function that called when writing is finished and pass this callback function to the first thread that writes data.

something like this

class WritingThread extends Thread {
private OnWritingCompleted callback;

public WritingThread(OnWritingCompleted callback){
this.callback = callback;
}

}

interface OnWritingCompleted {
void onCompleted()
}

you can pass this callback function to desired there like this

new WritingThread(new OnWritingCompleted { 
    override void onCompleted() {
    // start reading thread here 
    }
})

when the writing finished just do this

callback.onCompleted()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM