Why doesnt this Java loop in a thread work?

前端 未结 4 1843
挽巷
挽巷 2020-12-21 14:15

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 shou

相关标签:
4条回答
  • 2020-12-21 14:34

    shouldPlay should be volatile and please remove - shouldPlay = false;,

    if(shouldPlay)
     {
      //  shouldPlay = false;
          System.out.print("test");
     }
    
    0 讨论(0)
  • 2020-12-21 14:35

    The Java Memory Model only guarantees that threads will see changes made by other threads if they synchronize-with those threads. The Java Language Specification defines synchronized-with as follows:

    Synchronization actions induce the synchronized-with relation on actions, defined as follows:

    • An unlock action on monitor m synchronizes-with all subsequent lock actions on m (where subsequent is defined according to the synchronization order).
    • A write to a volatile variable (§8.3.1.4) v synchronizes-with all subsequent reads of v by any thread (where subsequent is defined according to the synchronization order).
    • An action that starts a thread synchronizes-with the first action in the thread it starts.
    • The write of the default value (zero, false or null) to each variable synchronizes-with the first action in every thread. Although it may seem a little strange to write a default value to a variable before the object containing the variable is allocated, conceptually every object is created at the start of the program with its default initialized values.
    • The final action in a thread T1 synchronizes-with any action in another thread T2 that detects that T1 has terminated. T2 may accomplish this by calling T1.isAlive() or T1.join().
    • If thread T1 interrupts thread T2, the interrupt by T1 synchronizes-with any point where any other thread (including T2) determines that T2 has been interrupted (by having an InterruptedException thrown or by invoking Thread.interrupted or Thread.isInterrupted).

    In your example, the thread writing shouldPlay and the thread reading it do none of that, thereby failing to establish synchronized-with. Therefore it is unspecified if and when the reading thread will notice the new value.

    In your case, declaring shouldPlay volatile is the easiest way to establish that synchronization.

    0 讨论(0)
  • 2020-12-21 14:42

    You can make use of AtomicBoolean as an alternative.

    0 讨论(0)
  • 2020-12-21 15:01

    add 'volatile' will fix it

    private volatile boolean shouldPlay = true;
    
    0 讨论(0)
提交回复
热议问题