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. }

你可能感兴趣的:(thread)