volatile是什么意思中文(volatile是什么意思)
大家好,小东方来为大家解答以上的问题。volatile是什么意思中文,volatile是什么意思这个很多人还不知道,现在让我们一起来看看吧!
1、一般的,如果多个线程协作存、取某个变量时,一般需要用到synchronized关键字进行同步操作。
2、如: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; }}。
本文到此分享完毕,希望对大家有所帮助。
免责声明:本文由用户上传,如有侵权请联系删除!
猜你喜欢
- 03-06
- 03-06
- 03-06
- 03-06
- 03-06
- 03-06
- 03-06
- 03-06