Reputation: 890
I have a Cell class representing a single value and swapThread class whose run method just call the method swapValue() in Cell.
public static void main(String[] args) throws InterruptedException {
Cell c1 = new Cell(15);
Cell c2 = new Cell(23);
Thread t1 = new swapThread(c1, c2);
Thread t2 = new swapThread(c2, c1);
t1.start();
t2.start();
}
class Cell:
class Cell {
private static int counter = 0;
private int value, id;
public Cell(int v) {
value = v;
id = counter++;
}
synchronized int getValue() {
return value;
}
synchronized void setValue(int v) {
value = v;
}
void swapValue(Cell other) {
int t = getValue();
System.out.println("Swapping " + t);
int v = other.getValue();
System.out.println("with " + v);
setValue(v);
other.setValue(t);
System.out.println("Cell is now " + getValue());
System.out.println("Cell was " + other.getValue());
}
}
and class swapThread:
class swapThread extends Thread {
Cell cell, othercell;
public swapThread(Cell c, Cell oc) {
cell = c;
othercell = oc;
}
public void run() {
cell.swapValue(othercell);
}
}
Usual output:
Swapping 15
Swapping 23
with 23
with 15
Cell is now 23
Cell is now 15
Cell was 15
Cell was 23
I can just wait for the thread1 to finish with Thread.join() in the main method but is there a way to avoid that by changing the synchronized methods.
Upvotes: 2
Views: 73
Reputation: 14338
You can achieve serial execution of swapValues()
by making this method static and synchronized:
static synchronized void swapValues(Cell c1, Cell c2) {
int t = c1.getValue();
System.out.println("Swapping " + t);
int v = c2.getValue();
System.out.println("with " + v);
c1.setValue(v);
c2.setValue(t);
System.out.println("Cell is now " + c1.getValue());
System.out.println("Cell was " + c2.getValue());
}
Thus, you synchronize it on Cell.class
, making swapValues()
to be performed sequentially.
Notice, now you need to pass 2 cells in it:
public void run() {
Cell.swapValues(cell, othercell);
}
Upvotes: 1