Java Interthread Communication不传递消息对象

时间:2015-03-17 01:10:15

标签: java multithreading listener communication

为了在线程之间进行通信,我遵循了Oracle Guarded Blocks example,它很容易编译并运行。我的架构略有不同,因为我的消费者产生了生产者任务,虽然我尝试了这个变化与示例,它完美地工作。

我主程序的相关代码;

public static void main(String[] args) {
...
    FrameMsg frameMsg = new FrameMsg();
    AwarenessAnalytics awarenessAnalytic = new AwarenessAnalytics(frameMsg);
    awarenessAnalytic.start();

来自消费者线程的相关代码;

public class AwarenessAnalytics extends Thread implements MotionEventListener{
    FrameMsg frameMsg;
    FrameWithMotionDetection frameWithMotionDetection;

      public AwarenessAnalytics(FrameMsg frameMsg) {
        this.frameMsg = frameMsg;
        System.out.println("AwarenessAnalytic frameMsg = " + this.frameMsg.hashCode());
        }
 AdvancedVideoAnalytics tempIntermediateVA;
 tempIntermediateVA = new AdvancedVideoAnalytics(frameMsg);

public void run() {

    tempIntermediateVA.start();

    while (true) {
        // TODO: create loop to process frames from each video stream
        frameWithMotionDetection = new FrameWithMotionDetection();
        // interthread message from AdvancedAnalytic
        System.out.println("Waiting for FrameMsg");
        frameWithMotionDetection = frameMsg.take();
        System.out.println("FrameMsg received");
}

生产者任务的相关代码;

public class AdvancedVideoAnalytics extends Thread {
  FrameMsg frameMsg;
  FrameWithMotionDetection frameWithMotionDetection;

public AdvancedVideoAnalytics (FrameMsg frameMsg) {
    this.frameMsg = frameMsg;
    System.out.println("AdvancedVideoAnalytic frameMsg = " + this.frameMsg.hashCode());
 }

// the run method includes;

// Send frame and any clusters detected
// as frameMsg
frameWithMotionDetection = new FrameWithMotionDetection();

frameWithMotionDetection.setMotionData(contourAnalysisResults);

frameWithMotionDetection.setCurrentFrame(frameToExamine);
System.out.println("Preparing to send message to AwarenessAnalytics thread");
frameMsg.put(frameWithMotionDetection);

FrameMsg类;

public class FrameMsg {
// Message sent from video stream monitors to analytic fusion engine

private FrameWithMotionDetection frameWithMotionData;

//private String message;
// True if consumer should wait
// for producer to send message,
// false if producer should wait for
// consumer to retrieve message.
private boolean empty = true;

public synchronized FrameWithMotionDetection take() {
    // Wait until message is
    // available.
    System.out.println("Getting ready to take frameWithMotionData");
    while (empty) {
        try {
            wait(10);
            System.out.println("Waiting to take frameWithMotionData because empty = true");
        } catch (InterruptedException e) {}
    }
    // Toggle status.
    empty = true;
    System.out.println("Successfully took frameWithMotionData, empty = " + empty);
    // Notify producer that
    // status has changed.
    notifyAll();
    return frameWithMotionData;
}

public synchronized void put(FrameWithMotionDetection frameWithMotionData) {
    // Wait until message has
    // been retrieved.
    System.out.println("Getting ready to put frameWithMotionData");
    while (!empty) {
        try { 
            System.out.println("Waiting to put frameWithMotionData because empty = false");
            wait();
        } catch (InterruptedException e) {}
    }
    // Toggle status.
    empty = false;
    // Store message.
    this.frameWithMotionData = frameWithMotionData;
    System.out.println("Successfully put frameWithMotionData, empty = " + empty);
    // Notify consumer that status
    // has changed.
    notifyAll();
}

}

有趣的是,所有的frameMsg对象id都是相同的,我能够'生成'一个frameMsg并从生产者处将空值设置为false。但是,消费者看到的frameMsg对象总是返回'true'表示空。

输出提取看起来像;

VideoAnalyticsUnitTest frameMsg = 1704856573
AwarenessAnalytic frameMsg = 1704856573
AdvancedVideoAnalytic frameMsg = 1704856573

Waiting to take frameWithMotionData because empty = true
Waiting to take frameWithMotionData because empty = true
(many of these)...
Preparing to send message to AwarenessAnalytics thread
Getting ready to put frameWithMotionData
Successfully put frameWithMotionData, empty = false
Waiting to take frameWithMotionData because empty = true
Preparing to send message to AwarenessAnalytics thread
Getting ready to put frameWithMotionData
Waiting to put frameWithMotionData because empty = false
Waiting to take frameWithMotionData because empty = true
Waiting to take frameWithMotionData because empty = true
Waiting to take frameWithMotionData because empty = true

在我终止程序之前,它会像最后三行一样继续。

我很困惑,因为; 我跟着这个例子 2.对象ID匹配

然而,消费者永远不会看到非空的frameMsg(这是一个复杂的对象)。

我错过了一些明显的东西吗?

我最初使用监听器发送消息,但我不想要一个巨大的应用程序占用监听器空间。现在阅读更多的评论,似乎我可以使用监听器并使用阻塞队列将消息传递给消费者的运行部分。

如果是你,你会采用上面的通信方法,还是回到带阻塞队列的监听器?

2 个答案:

答案 0 :(得分:1)

如果要更新synchronized参数而不使用,请不要使用empty方法 synchronized阻止

synchronized(this){
//work from here for core logic 

}
//empty =true logic or empty = false

块比方法有优势,最重要的是灵活性,因为你可以使用其他对象作为锁,而同步方法会锁定整个类。

比较

// locks the whole object
... 
private synchronized void someInputRelatedWork() {
... 
}
private synchronized void someOutputRelatedWork() {
... 
}

Vs以上。

// Using specific locks
Object inputLock = new Object();
Object outputLock = new Object();

private void someInputRelatedWork() {
synchronize(inputLock) { 
    ... 
} 
}
private void someOutputRelatedWork() {
synchronize(outputLock) { 
    ... 
}
}

此外,如果方法增长,您仍然可以将同步部分分开:

 private void method() {
 ... code here
 ... code here
 ... code here
 synchronized( lock ) { 
    ...very few lines of code here
 }
 ... code here
 ... code here
 ... code here
 ... code here
}

最后一个建议是使用LinkedBlockingQueue,因为它有良好的性能影响并且有很好的方法put and take

答案 1 :(得分:1)

正如@Bhargav Modi指出的那样,代码遇到了编写多线程应用程序的更精细问题(synchronized-block与-method,对关键变量使用volatile声明)。这些问题在测试期间经常被遗漏,因为需要一个机会元素才能使问题出现(其中一个最臭名昭着的问题是double checked locking)。

这是使用Java concurrent类的一个很好的理由:编写非线程安全或具有多线程问题的代码的可能性较小。在您的情况下,SynchronousQueue看起来是一个很好的替代品。使用SynchronousQueue,无需使用empty变量,this.frameWithMotionData变量或wait / notifyAll机制。