我正在构建一个在多进程(线程)中使用的简单程序。
我的问题更容易理解 - 什么时候我必须使用保留字同步?
我是否需要在影响骨骼变量的任何方法中使用这个词?
我知道我可以将它放在任何非静态的方法上,但我想了解更多。
谢谢你!
这是代码:
public class Container {
// *** data members ***
public static final int INIT_SIZE=10; // the first (init) size of the set.
public static final int RESCALE=10; // the re-scale factor of this set.
private int _sp=0;
public Object[] _data;
/************ Constructors ************/
public Container(){
_sp=0;
_data = new Object[INIT_SIZE];
}
public Container(Container other) { // copy constructor
this();
for(int i=0;i<other.size();i++) this.add(other.at(i));
}
/** return true is this collection is empty, else return false. */
public synchronized boolean isEmpty() {return _sp==0;}
/** add an Object to this set */
public synchronized void add (Object p){
if (_sp==_data.length) rescale(RESCALE);
_data[_sp] = p; // shellow copy semantic.
_sp++;
}
/** returns the actual amount of Objects contained in this collection */
public synchronized int size() {return _sp;}
/** returns true if this container contains an element which is equals to ob */
public synchronized boolean isMember(Object ob) {
return get(ob)!=-1;
}
/** return the index of the first object which equals ob, if none returns -1 */
public synchronized int get(Object ob) {
int ans=-1;
for(int i=0;i<size();i=i+1)
if(at(i).equals(ob)) return i;
return ans;
}
/** returns the element located at the ind place in this container (null if out of range) */
public synchronized Object at(int p){
if (p>=0 && p<size()) return _data[p];
else return null;
}
使类能够安全地进行多线程访问是一个复杂的主题。如果您这样做不是为了了解线程,那么您应该尝试找到一个可以为您完成此操作的库。
话虽如此,首先要想象两个单独的线程以交替的方式逐行执行一个方法,然后看看会出现什么问题。例如,上面写的 add() 方法很容易受到数据破坏。想象一下线程 1 和线程 2 或多或少同时调用 add()。如果线程 1 运行第 2 行,并且在到达第 3 行之前,线程 2 运行第 2 行,则线程 2 将覆盖线程 1 的值。因此,您需要某种方法来防止线程像这样交错。另一方面,isEmpty() 方法不需要同步,因为只有一条指令将值与 0 进行比较。同样,很难正确处理这些内容。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)