如下两个线程类:
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!!
Try it
synchronized
, it has several granularities.It can be added to the code block like @scort, or it can be added to the object.
synchronized or ReentrantLock. Someone gave an example of synchronized before. I will give an example of ReentrantLock here:
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