public class Test {
private static class Resource {
public int value;
};
private Resource resourceA = new Resource();
private Resource resourceB = new Resource();
public int read() {
synchronized (resourceA) {
synchronized (resourceB) {
return resourceA.value + resourceB.value;
}
}
}
public void write(int a, int b) {
synchronized (resourceB) {
synchronized (resourceA) {
resourceA.value = a;
resourceB.value = b;
}
}
}
public static void main(String[] args) {
final Test test = new Test();
Runnable targetA = new Runnable() {
public void run() {
while (true)
System.out.println(test.read());
}
};
Runnable targetB = new Runnable() {
public void run() {
while (true)
test.write(1, 2);
}
};
new Thread(targetA).start();
new Thread(targetB).start();
}
}
Login in to like
Login in to comment