gpt4 book ai didi

java - 同步线程行为

转载 作者:行者123 更新时间:2023-11-30 11:04:45 25 4
gpt4 key购买 nike

我有一个代表单个值的 Cell 类swapThread 类,它的运行方法只是调用 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());
}

}

类swapThread:

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 完成,但是有没有办法通过更改同步方法来避免这种情况。

最佳答案

您可以通过将此方法设为静态和同步来实现 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);
}

关于java - 同步线程行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29918281/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com