如何保证在多线程场景中依次使用类链发送消息

时间:2017-05-11 22:33:35

标签: java multithreading

我使用链A-B-C发送暂停和播放的Message。我想保证Class C发送消息PAUSE,然后按顺序播放。 (我希望C发送PAUSE-PLAY,但有时会变成PLAY-PAUSE)。

目前,我在A的每个sendMessage中添加了1秒睡眠。但我认为这不是线程安全的。

那么实现这个顺序目标的最佳方法是什么?

   [testng] B sending event PAUSE 7951016310326825
   [testng] B sending event PLAY 7951016310683642
   [testng] C sending event PLAY 7951016311536353
   [testng] C sending event PAUSE 7951016311575708

public Class A {
    Private B b;
    @Override
    public void processCommand(Message)
    throws Exception {
    onPause(Message);
    onPlay(Message);
    }

    private void onPause(Message) {
        b.process(Message);
    }

    private void onPlay(Message) {
        b.process(Message);
    }
}


public Class B implements Runnable {
    private C c;
    protected Boolean isRunning = true;
    protected Thread runThread;

    public void process(Message) {
        System.out.println("B Sending message " + Message.id);
    }

    @Override
    public void run(){
    }

    public void startup()
    throws Exception
    {
        this.runThread = new Thread(this, this.subsystemId);
        this.isRunning = true;
        this.runThread.start();
    }
}

public Class C {
    public void process(Message) {
        System.out.println("C Sending message " + Message.id);
    }
}

0 个答案:

没有答案