将线程中的停止标志设置为true,线程是否为空?

时间:2018-04-30 07:51:18

标签: java multithreading iot

显然,我目前的做法并不是应该如何做,因为它不起作用。 我的项目是根据从Web服务器收到的时间表播放音频的软件。

我有三个线程,一个线程是一个侦听器,它在Web套接字上侦听是否有我们应该下载的新计划的通知。该线程启动另一个线程,它是一个" Schedule Downloader",这使得http请求和下载文件。当它启动时它会检查计划并下载文件,在执行此操作后,如果有一个标志设置为false并且标志上有while循环,那么该线程仍在运行但在该标志更改之前没有做任何事情。此标志为boolean newSchedule。当它完成时,它启动一个线程来播放音乐

我目前设置的方式是我的侦听器onMessage()中的方法MyTopicClass更改了日程安排下载程序中的标志,以便再次开始下载日程安排。我可以通过调试看到这个工作。收到通知会调用我的getScheduleAgain()类中的ScheduleDownloader方法,该方法会更改标记,我的代码会再次开始检查/下载计划。我可以看到这个工作正常。什么不起作用我想要的是我试图在我的AudioPlayer中设置一个标志,这样它就完成了所以我可以用新的计划开始新的标志。出现问题的是当我在我的setStopFlagToTrue()方法中调用我的音频播放器上的getScheduleAgain()时,根据调制器,音频播放器是null

因此,当我的MyTopic侦听器线程收到通知时,我的工作流程为IotClient,它会在onMessage()中调用myTopic来调用我的getScheduleAgain()我的Scheduledownloader。这一切都按预期工作,除了我的getScheduleAgain()方法在我的audioplayer线程上调用setStopFlagToTrue但根据调试器调用null

Main.java

      IotClient client = new IotClient("username");
  client.start();

IotClient

     public class IotClient extends Thread {
   Thread t;
   String username;
   ScheduleDownloader downloader;
public IotClient(String username)  {
    this.username = username;
    downloader = new ScheduleDownloader("username,","password2","thread");
}
   public void run(){
    this.currentThread().setPriority(Thread.MAX_PRIORITY);
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
String clientEndpoint = "removed my end point here";       
// replace <prefix> and <region> with your own
String clientId = "1";                              // replace with your own client ID. Use unique client IDs for concurrent connections.

// AWS IAM credentials could be retrieved from AWS Cognito, STS, or other secure sources
AWSIotMqttClient client = new AWSIotMqttClient(clientEndpoint, clientId, "removed credentials ", "removed credentials");

// optional parameters can be set before connect()
try {
    client.connect();
} catch (AWSIotException e) {
    e.printStackTrace();
}
AWSIotQos qos = AWSIotQos.QOS0;
new ScheduleDownloader("dunnesdrogheda","password2","thread").start();
AWSIotTopic topic = new MyTopic("schedule/"+ username, qos,downloader);

try {
    client.subscribe(topic, true);
} catch (AWSIotException e) {
    e.printStackTrace();
}

while(true){
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
}
public void start(){
if (t == null) {
    t = new Thread (this, "IotClientThread");
    t.start ();
}
}


  }

MyTopic

public class MyTopic extends AWSIotTopic {
ScheduleDownloader downloader;

public MyTopic(String topic, AWSIotQos qos, ScheduleDownloader downloader) {

    super(topic, qos);
    this.downloader = downloader;
}

@Override
public void onMessage(AWSIotMessage message) {
    System.out.println("Message recieved from topic: "+ message.getStringPayload());
    try {
        downloader.getScheduleAgain();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

}
}

ScheduleDownloader,删除了用于下载文件的不相关的util方法

public class ScheduleDownloader extends Thread {
private Thread t;
private String threadName;

    String username;
    String password;
     volatile boolean newSchedule = true;
     AudioPlayer audioPlayer;

    public ScheduleDownloader(String username,String password,String threadName){
        this.username = username;
        this.password = password;
        this.threadName= threadName;
    }
    public void startPlayerThread(){

    }
    public void startAudioPlayer(Schedule schedule) throws UnsupportedAudioFileException, IOException, LineUnavailableException {
        audioPlayer = new AudioPlayer(schedule);
        audioPlayer.start();
    }
 public void start () {
    System.out.println("Starting " +  threadName );
    if (t == null) {
        t = new Thread (this, threadName);
        t.start ();
    }}
public synchronized void run() {
    try {

  while(true){
Thread.sleep(1000);
        while(newSchedule == true) {
            Schedule schedule = null;
            while (schedule == null) {
                System.out.println("Searching for schedule");
                schedule = getTodaysSchedule();
            }
            System.out.println("Schedule Found");
            boolean result = false;
            while (result == false) {
                result = downloadFiles(schedule);
            }
            System.out.println("Files Downloaded");
            startAudioPlayer(schedule);

            newSchedule = false;

         }
       }
    } catch (IOException e) {
        e.printStackTrace();
    }  catch (UnsupportedAudioFileException e) {
        e.printStackTrace();
    } catch (LineUnavailableException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
public void getScheduleAgain() throws InterruptedException {
        this.audioPlayer.setStopFlagToTrue();
        Thread.sleep(4000);
        newSchedule = true;
}

AudioDownloader,checkShouldWePlayAnAdvertisement是循环的方法,直到结束标志被设置为true

public class AudioPlayer extends Thread {
Long currentFrameMusic;
Long currentFrameAdvertisement;
Clip clipMusic;
Clip clipAdvertisement;
private Thread t;
private volatile boolean stopFlag = false;

// current status of clip
String statusMusic;
String statusAdvertisement;

static AudioInputStream musicInputStream;
static AudioInputStream advertisementInputStream;
static String filePath;
Schedule schedule;

// constructor to initialize streams and clip
public AudioPlayer(Schedule schedule)
        throws UnsupportedAudioFileException,
        IOException, LineUnavailableException
{
    //setup audio stream for music first
    // create AudioInputStream object
this.schedule = schedule;
    appendMusicFiles(schedule);

    // create clip reference
    clipMusic = AudioSystem.getClip();

    // open audioInputStream to the clip
    clipMusic.open(musicInputStream);

    clipMusic.loop(Clip.LOOP_CONTINUOUSLY);
}

public void run(){
    playMusic();
    try {
        checkShouldWePlayAnAdvertisement();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (UnsupportedAudioFileException e) {
        e.printStackTrace();
    } catch (LineUnavailableException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    try {
        checkShouldWePlayAnAdvertisement();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (UnsupportedAudioFileException e) {
        e.printStackTrace();
    } catch (LineUnavailableException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    try {
        checkShouldWePlayAnAdvertisement();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (UnsupportedAudioFileException e) {
        e.printStackTrace();
    } catch (LineUnavailableException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
public void start(){
    t = new Thread (this, "AudioPlayerThread");
    t.start ();
}
public void checkShouldWePlayAnAdvertisement() throws IOException, UnsupportedAudioFileException, LineUnavailableException, InterruptedException {
    ArrayList<String> playedAtTimes = new ArrayList<>();
    ArrayList<Advertisement> advertisementsToBePlayed = new ArrayList<>();
    boolean found;
    //played at times is used to keep track of what time we played advertisements
    //so when the loop reruns and the time hasnt changed it doesnt play it again
    while(stopFlag ==false){
        Thread.sleep(1000);
        found = false;
        ZonedDateTime zdt = ZonedDateTime.now();
        String timeHHMM =zdt.toString().substring(11,16);
        for(int i =0;i<schedule.getAdvertisementScheduleItems().size();i++){
            if(schedule.getAdvertisementScheduleItems().get(i).getTimes().contains(timeHHMM)){
                //this item should be played now
                if(playedAtTimes.contains(timeHHMM)){
                    //we already played this,but the time hasnt changed when the loop ran again
                }else{
                    advertisementsToBePlayed.add(schedule.getAdvertisementScheduleItems().get(i).getAdvertisement());
                    found = true;
                }
            }
        }
        if(found== true) {
            playedAtTimes.add(timeHHMM);
            appendAdvertisementFiles(advertisementsToBePlayed);
            pauseMusic();
            playAdvertisements();
            stopAdvertisement();

            resumeAudioMusic();
        }
    }

    System.out.println("audio player is closing");
 clipMusic.close();
}
public synchronized void setStopFlagToTrue(){
    stopFlag = true;
}

1 个答案:

答案 0 :(得分:0)

在IotClient.java中,您创建了两个ScheduleDownloader实例。

public IotClient(String username) {
        this.username = username;
        downloader = new ScheduleDownloader("username,", "password2", "thread");
    }

new ScheduleDownloader("dunnesdrogheda", "password2", "thread").start();
        AWSIotTopic topic = new MyTopic("schedule/" + username, qos, downloader); 

你已经将1个实例传递给了AWSIotTopic并使用了另一个实例来生成带有while(true)的线程

来自MyTopic.java的ScheduleDownloader实例甚至不知道audioPlayer并且给出了nullPointerException。

尝试使用相同的ScheduleDownloader实例或将audioPlayer定义为public static,它应该可以正常工作。