2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

sharing an object between threads.

As per my requirement i want to share an object between threads.So to pass a thread between them.
userimage

Getting the two threads to share the array safely is a bit harder. The problem is that the two threads need to synchronize. The send thread needs to know what part of the array that the record thread has written to. Furthermore, synchronization is necessary to ensure that data written by the record thread is visible to the send thread.

Here is a piece of code snippet as an example to make you understand and to fulfill your requirement too.

Lets say we have two threads. One records the audio data into the variable and another Thread sends that recorded variable to the server. What do I need to do in terms of concurrency, since I am new to multi-threading?


short[] sData = new short[1024];

recordingThread = new Thread(new Runnable() {
        public void run() {
            android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
            while (isRecording) {
                recorder.read(sData, 0, BufferElements2Rec);
            }

        }
    }, "AudioRecorder Thread");
    recordingThread.start();


Thread sendThread= new Thread(new Runnable() {
    public void run() {
                android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
    while (true) {
        try {

      ByteBuffer.wrap(bData).order(ByteOrder.LITTLE_ENDIAN)
            .asShortBuffer().put(sData);           
        }
    }
});


Answer is