为什么此Java循环在线程中不起作用? [英] Why doesnt this Java loop in a thread work?

查看:117
本文介绍了为什么此Java循环在线程中不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Java编写无线电,并且正在使用线程来当然播放流.我在线程的run方法中有一个while循环,该循环检查名为ShouldPlay的变量是否为true,以及是否为true它运行播放器.然后,我有一个pause()方法,将变量设置为false,并且自然希望它在变量为false时不运行播放器.我创建了一个小示例,说明如何在下面进行设置:

I'm coding a radio in java and am using a thread to of course play the stream in. I have a while loop in the run method of the thread which checks if a variable called shouldPlay is true, and if it is it runs the player. Then, I have a pause() method which sets the variable to false and naturally I want it to not run the player when the variable is false. I've created a small example of how I've set it up below:

class audiostream extends Thread {

    private boolean shouldPlay = true;

    @Override
    public void run() {
        while(true)
        { 
            if(shouldPlay)
            {
                shouldPlay = false;
                System.out.print("test");
            }
        }
    }

    public void pause() {
        shouldPlay = false;
    }

    public void play() {
        shouldPlay = true;
    }

}

我要发生的事情是当线程首次运行时,它应该打印"test"(效果很好).然后,当您运行pause()时,应将shouldPlay设置为false,并且不允许打印"test".但是,当您调用play()时,应将shouldPlay设置为true,然后再次打印出测试.问题是它没有这样做.

What I want to happen is when the thread first runs, it should print "test" (which it does fine). Then when you run pause() it should set shouldPlay to false and not allow "test" to be printed out. But then when you call play() it should set shouldPlay to true then print out test again. The problem is it's not doing this.

大约是它的1/100.我是否可以假设问题出在这里,即使我从另一个线程调用play()和pause()也不是要挂起"父线程,即我的子线程挂在while循环上以及调用play()或来自父级的pause()变量不会因为该循环而改变值?如果是这样,我不知道该怎么办!

About 1/100th of the time it will though. Am I right to assume the problem here is even though I call play() and pause() from another thread as not to "hang" the parent thread, that my child thread is hanging on that while loop and when calling play() or pause() from the parent the variables don't change value because of that loop? If that's the case I don't know what I should do!

推荐答案

添加'volatile'会解决

add 'volatile' will fix it

private volatile boolean shouldPlay = true;

这篇关于为什么此Java循环在线程中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆