Java中volatile的用處

來源:互聯網
上載者:User

Java中volatile的用處

今天由於要寫一個線程進程,無意中看到了volatile的用法,覺得非常有用。 一般的,如果多個線程協作存、取某個變數時,一般需要用到synchronized關鍵字進行同步操作,如:
public class
MyTestThread extends MyTest implements Runnable {
    private boolean _done =
false;    public synchronized boolean getDone()
    {
        return
_done;
    }
    public synchronized void setDone(boolean b)
   
{
        _done = b;
    }
   
    public void run( ) {
       
boolean done;
        done = getDone();
        while (!done)
{
            repaint( );
            try {
               
Thread.sleep(100);
            } catch (InterruptedException ie)
{
                return;
            }
        }
    }
}或者:
public class MyTestThread extends MyTest implements Runnable
{
    private boolean _done = false;    public void setDone(boolean b)
    {
       
synchronized(this)
        {
            _done = b;
        }
   
}
   
    public void run( ) {
        boolean done;
       
synchronized(this)
        {
            done = _done;
       
}
       
        while (!done) {
            repaint(
);
            try {
                Thread.sleep(100);
            }
catch (InterruptedException ie) {
                return;
           
}
        }
    }
}但是,通過volatile關鍵字,我們可以大大簡化:
public class MyTestThread extends MyTest
implements Runnable {
    private volatile boolean done = false;    public void run( ) {
        while (!done) {
            repaint(
);
            try {
                Thread.sleep(100);
            }
catch (InterruptedException ie) {
                return;
           
}
        }
    }    public void setDone(boolean b) {
        done = b;
   
}
}相關的介紹如下:
Java specifies that basic loading and storing of variables
(except for long and double variables) is atomic. That means the value of the
variable can't be found in an interim state during the store, nor can it be
changed in the middle of loading the variable to a register. The setDone()
method has only one store operation; therefore, it is atomic.Unfortunately, Java's memory model is a bit more complex. Threads are
allowed to hold the values of variables in local memory (e.g., in a machine
register). In that case, when one thread changes the value of the variable,
another thread may not see the changed variable. This is particularly true in
loops that are controlled by a variable (like the done flag that we are using to
terminate the thread): the looping thread may have already loaded the value of
the variable into a register and does not necessarily notice when another thread
changes the variable.One way to solve this problem is to provide setter and getter methods for
the variable. We can then simply synchronize access by using the synchronized
keyword on these methods.However, Java provides a more elegant solution: the volatile keyword. If a
variable is marked as volatile, every time the variable is used it must be read
from main memory. Similarly, every time the variable is written, the value must
be stored in main memory.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.