多线程 - java 线程同步问题
PHP中文网
PHP中文网 2017-04-18 09:50:26
0
5
454

如下两个线程类:

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中文网

认证高级PHP讲师

reply all(5)
阿神
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()){
        
        }
        
        .......
    }
}
Ty80

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

PHPzhong

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();  
} 
Ty80

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

大家讲道理

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!