开发者

Java multithreading synchronization problem

开发者 https://www.devze.com 2023-03-25 00:52 出处:网络
I\'m having some issues with java multithreading, best explained on an example: class Thread1 extends Thread

I'm having some issues with java multithreading, best explained on an example:

    class Thread1 extends Thread
    {
        boolean val=false;


        public void set()
        {       
            val=true;
        }


        public void run()
        {

        while (true)
        {

            if(val==true)
            {
                System.out.println("true");
                val=false;
            }

            try
            {
                sleep(1);
            }
            catch (InterruptedException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }   

    }
}

So this is a simple class which is ran in a separate thread.

Now consider this case: 1) I start the thread in the class above 2) from some other thread I call the Thread1.set() function 3) the condition on the Thread1.run() function evaluates to true

Now, the thing is that if I remove the sleep(1) from the above code, this condition is never set to true.

So my question is: is there any other way I can interrupt the run() function so that other functions may set the variables that would be used inside the run()function? (I'm making a game on Android, so the openGL renderer runs in one thread and my game logic thread would run in another t开发者_开发技巧hread and I would like to sync them every frame or two),


If only a single thread (i.e. one other than the thread reading it) is modifying val, then make it volatile.


Your boolean variable is not volatile which means there is no guarantee that two different threads are seeing the same value. By sleeping it the virtual machine might cause the value set from a different thread to become visible to the thread (this is a guess - nothing more), but this behavior should not be relied upon in any way. You should either use a volatile boolean variable or an AtomicBoolean class depending on your needs.

0

精彩评论

暂无评论...
验证码 换一张
取 消