import java.awt.Dimension;
/***Example class.The x and y values should never*be negative.*/
public class Example{
private Dimension d = new Dimension (0, 0);
public Example (){ }
/*** Set height and width. Both height and width must be nonnegative * or an exception is thrown.*/
public synchronized void setValues (int height,int width) throws IllegalArgumentException{
if (height < 0 || width < 0)
throw new IllegalArgumentException();
d.height = height;
d.width = width;
}
/*** Example class.The value should never * be negative.*/
public class Example{
private Integer i = new Integer (0);
public Example (){ }
/*** Set x. x must be nonnegative* or an exception will be thrown*/
public synchronized void setValues (int x) throws IllegalArgumentException{
if (x < 0)
throw new IllegalArgumentException();
i = new Integer (x);
}
public synchronized Integer getValue(){
// We can’t clone Integers so we makea copy this way.
return new Integer (i.intValue());
}
}
public class Example{
private int[] copy;
/*** Save a copy of ’data’. ’data’ cannot be null.*/
public void saveCopy (int[] data){
copy = new int[data.length];
for (int i = 0; i < copy.length; ++i)
copy = data;
}
}
import java.awt.Dimension;
/*** Example class. The height and width values should never * be
negative. */
public class Example{
static final public int TOTAL_VALUES = 10;
private Dimension[] d = new Dimension[TOTAL_VALUES];
public Example (){ }
/*** Set height and width. Both height and width must be nonnegative * or an exception will be thrown. */
public synchronized void setValues (int index, int height, int width) throws IllegalArgumentException{
if (height < 0 || width < 0)
throw new IllegalArgumentException();
if (d[index] == null)
d[index] = new Dimension();
d[index].height = height;
d[index].width = width;
}
public synchronized Dimension[] getValues()
throws CloneNotSupportedException{
return (Dimension[])d.clone();
}
}
public class Example{
private int value; // More code here...
public void set (int x){
// NOTE: No synchronized keyword
this.value = x;
}
}
不过,这个保证仅限于读和写,下面的代码不是线程安全的:
public void increment (){
// This is effectively two or three instructions:
// 1) Read current setting of ’value’.
// 2) Increment that setting.
// 3) Write the new setting back.
++this.value;
}