volatile

  1. 一般的,如果多个线程协作存、取某个变量时,一般需要用到synchronized关键字进行同步操作,如:
  2. publicclassMyTestThreadextendsMyTestimplementsRunnable{
  3. privateboolean_done=false;
  4. publicsynchronizedbooleangetDone()
  5. {
  6. return_done;
  7. }
  8. publicsynchronizedvoidsetDone(booleanb)
  9. {
  10. _done=b;
  11. }
  12. publicvoidrun(){
  13. booleandone;
  14. done=getDone();
  15. while(!done){
  16. repaint();
  17. try{
  18. Thread.sleep(100);
  19. }catch(InterruptedExceptionie){
  20. return;
  21. }
  22. }
  23. }
  24. }
  25. 或者:
  26. publicclassMyTestThreadextendsMyTestimplementsRunnable{
  27. privateboolean_done=false;
  28. publicvoidsetDone(booleanb)
  29. {
  30. synchronized(this)
  31. {
  32. _done=b;
  33. }
  34. }
  35. publicvoidrun(){
  36. booleandone;
  37. synchronized(this)
  38. {
  39. done=_done;
  40. }
  41. while(!done){
  42. repaint();
  43. try{
  44. Thread.sleep(100);
  45. }catch(InterruptedExceptionie){
  46. return;
  47. }
  48. }
  49. }
  50. }
  51. 但是,通过volatile关键字,我们可以大大简化:
  52. publicclassMyTestThreadextendsMyTestimplementsRunnable{
  53. privatevolatilebooleandone=false;
  54. publicvoidrun(){
  55. while(!done){
  56. repaint();
  57. try{
  58. Thread.sleep(100);
  59. }catch(InterruptedExceptionie){
  60. return;
  61. }
  62. }
  63. }
  64. publicvoidsetDone(booleanb){
  65. done=b;
  66. }
  67. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值