java中volatile关键字的使用

一般的,如果多个线程协作存、取某个变量时,一般需要用到synchronized关键字进行同步操作,如:

//MyTest类中的repaint()方法用于不段的调用_done属性
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,thread,IE)