简体   繁体   English

如何在两个线程之间共享对象(线程同步)?

[英]How to Share a Object between two threads (Thread Synchronization)?

I have two threads. 我有两个主题。 One records the audio data into the variable. 一个人将音频数据记录到变量中。 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? 由于我不熟悉多线程,因此我需要在并发性方面做些什么?

Below is the code snippet: 以下是代码段:

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();

and another Thread which is accessing same sData and sending it to the server: 和另一个访问相同sData并将其发送到服务器的线程:

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);            
        }
    }
});

To minimize reinventing the wheel, you can implement it as producer/consumer synchronization.For starters: 为了最大限度地减少重新发明轮子,您可以将其实现为生产者/消费者同步。对于初学者:

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/ArrayBlockingQueue.html http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/ArrayBlockingQueue.html

Just in case, some introductory stuff is here: 以防万一,一些介绍性的东西在这里:

http://en.wikipedia.org/wiki/Producer-consumer_problem http://en.wikipedia.org/wiki/Producer-consumer_problem

There are two aspects to your question. 你的问题有两个方面。

  • Assuming that sData is a local variable, all you need to do to get the two Threads to share the array is to declare sData as final . 假设sData是一个局部变量,你需要做的就是让两个Threads共享数组是将sData声明为final (And if sData is an instance or class variable you don't even need to do that ...) (如果sData是一个实例或类变量,你甚至不需要这样做......)

  • 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. 此外,同步是必要的,以确保记录线程写入的数据对发送线程可见。

In this example, proper synchronization will most likely entail a couple of extra variables to indicate the current positions of the two threads. 在这个例子中,正确的同步很可能需要一些额外的变量来指示两个线程的当前位置。 And since you have to deal with the cases where one thread needs to wait for the other to add or send data, you probably need to use Object.wait() and Object.notify() to avoid busy waiting. 而且由于您必须处理一个线程需要等待另一个线程添加或发送数据的情况,您可能需要使用Object.wait()Object.notify()来避免繁忙等待。


But what you are doing at the semantic level looks as if it needs to operate like a classical circular buffer of short values. 但是你在语义层面上所做的事情看起来好像需要像short值的经典循环缓冲区一样运行。 So I'd recommend looking for an existing implementation that you can reuse. 所以我建议您寻找可以重复使用的现有实现。 (For example, if you were willing to take the overhead of Short versus short then you could use an ArrayBlockingQueue<Short> .) (例如,如果您愿意承担Shortshort的开销,那么可以使用ArrayBlockingQueue<Short> 。)

处理此问题的一种方法是使用锁存器(如果这是一次性操作)或CyclicBarrier(如果需要重复)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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