同步线程行为

0pizxfdo  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(403)

我有一个表示单个值的cell类和swapthread类,其run方法只调用cell中的swapvalue()方法。

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 {
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());
}

}

和类交换线程:

class swapThread extends Thread {
Cell cell, othercell;

public swapThread(Cell c, Cell oc) {
    cell = c;
    othercell = oc;
}

public void run() {

    cell.swapValue(othercell);

}
}

通常输出:

Swapping 15
Swapping 23
with 23
with 15
Cell is now 23
Cell is now 15
Cell was 15
Cell was 23

我可以在main方法中使用thread.join()等待thread1完成,但是有没有办法通过更改synchronized方法来避免这种情况。

qojgxg4l

qojgxg4l1#

您可以实现 swapValues() 通过使此方法保持静态和同步:

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());
}

因此,您可以在 Cell.class ,制作 swapValues() 按顺序进行。
请注意,现在需要在其中传递2个单元格:

public void run() {
    Cell.swapValues(cell, othercell);
}

相关问题