search

Home  >  Q&A  >  body text

多线程 - java 线程同步问题

如下两个线程类:

public class A implements Runnable{
    private StringBuilder sb;
    
    @Override
    public void run() {
        //操作sb缓冲
        .......
    }
    public StringBuilder getsb() {
        return sb;
    }

    public void setsb(StringBuilder sb) {
        this.sb = sb;
    }
}

public class B implements Runnable{
    //此处得到A类的对象a
    
    @Override
    public void run() {
        //操作a.getsb()缓冲
        .......
    }
}

如何能保证,A、B互斥?

A的线程在操作sb的时候加锁,让B不能操作;或者B的线程在操作sb的时候加锁,让A不能操作

始终只有一个线程可以操作sb!!

PHP中文网PHP中文网2809 days ago473

reply all(5)I'll reply

  • 阿神

    阿神2017-04-18 09:52:26

    public class A implements Runnable{
        private StringBuilder sb;
        
        @Override
        public void run() {
            //操作sb缓冲
            
            synchronized(sb){
            
            }
            .......
        }
        public StringBuilder getsb() {
            return sb;
        }
    
        public void setsb(StringBuilder sb) {
            this.sb = sb;
        }
    }
    
    public class B implements Runnable{
        //此处得到A类的对象a
        
        @Override
        public void run() {
            //操作a.getsb()缓冲
            synchronized(a.getsb()){
            
            }
            
            .......
        }
    }

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 09:52:26

    Try itsynchronized, it has several granularities.
    It can be added to the code block like @scort, or it can be added to the object.

    reply
    0
  • PHPz

    PHPz2017-04-18 09:52:26

    synchronized or ReentrantLock. Someone gave an example of synchronized before. I will give an example of ReentrantLock here:

    ReentrantLock lock = new ReentrantLock(); 
    lock.lock();  
    try {  
        // 这里是对sb的操作  
    } finally {  
        lock.unlock();  
    } 

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 09:52:26

    At this time, you can consider using StringBuffer directly. The only difference from StringBuilder is that the former is thread-safe.

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-18 09:52:26

    I personally think you should put forward the method that requires thread execution first, then add a lock to the method, and then remove multiple threads and it should be possible

    reply
    0
  • Cancelreply