- 一般的,如果多个线程协作存、取某个变量时,一般需要用到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
最新推荐文章于 2024-12-03 15:10:42 发布