- 一般的,如果多个线程协作存、取某个变量时,一般需要用到synchronized关键字进行同步操作,如:
- publicclassMyTestThreadextendsMyTestimplementsRunnable{
- privateboolean_done=false;
- publicsynchronizedbooleangetDone()
- {
- return_done;
- }
- publicsynchronizedvoidsetDone(booleanb)
- {
- _done=b;
- }
- publicvoidrun(){
- booleandone;
- done=getDone();
- while(!done){
- repaint();
- try{
- Thread.sleep(100);
- }catch(InterruptedExceptionie){
- return;
- }
- }
- }
- }
- 或者:
- publicclassMyTestThreadextendsMyTestimplementsRunnable{
- privateboolean_done=false;
- publicvoidsetDone(booleanb)
- {
- synchronized(this)
- {
- _done=b;
- }
- }
- publicvoidrun(){
- booleandone;
- synchronized(this)
- {
- done=_done;
- }
- while(!done){
- repaint();
- try{
- Thread.sleep(100);
- }catch(InterruptedExceptionie){
- return;
- }
- }
- }
- }
- 但是,通过volatile关键字,我们可以大大简化:
- publicclassMyTestThreadextendsMyTestimplementsRunnable{
- privatevolatilebooleandone=false;
- publicvoidrun(){
- while(!done){
- repaint();
- try{
- Thread.sleep(100);
- }catch(InterruptedExceptionie){
- return;
- }
- }
- }
- publicvoidsetDone(booleanb){
- done=b;
- }
- }
volatile
最新推荐文章于 2025-08-22 11:29:57 发布
本文探讨了在Java中使用Volatile关键字简化线程间变量同步的方法,对比了传统的Synchronized关键字,展示了如何利用Volatile减少代码复杂度并保持线程安全性。
1286

被折叠的 条评论
为什么被折叠?



