gpt4 book ai didi

java - 想要一个代码来了解同步方法和异步方法之间的区别

转载 作者:行者123 更新时间:2023-12-02 07:52:21 24 4
gpt4 key购买 nike

我正在尝试设置同步和非同步方法之间的差异。我尝试过以下代码

 class Counter {
private int counter = 10;
public int getCounter() {
return counter;
}

public synchronized void doIncrementAndDecrement() {
counter++;
keepBusy(500);
counter--;
}

public void keepBusy(int howLong) { // (D)
long curr = System.currentTimeMillis();
while (System.currentTimeMillis() < curr + howLong)
;
}
}

class MyCounterThread extends Thread {

Counter c;

public MyCounterThread(Counter c, String name) {
// TODO Auto-generated constructor stub
super(name);
this.c = c;
start();
}

@Override
public void run() {
for (;;) {
c.doIncrementAndDecrement();
sleepForSometime();
System.out.println(c.getCounter());
}
}

public void sleepForSometime() { // (D)
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public class UnSynchronizedExapmle {

public static void main(String[] args) throws InterruptedException {
Counter c = new Counter();
MyCounterThread t1 = new MyCounterThread(c, "A");
MyCounterThread t2 = new MyCounterThread(c, "B");
MyCounterThread t3 = new MyCounterThread(c, "C");
}
}

所以上面我有 doIncrementAndDecrement() 同步方法..

所以我预计计数器的值每次都应该是10。但这不会发生,我的输出就像

10
10
11
10
10
10
10
11
10
10
11
10
11
11
10
10
11
10
11
10
10
10
11
10
10
11
10

所以请帮助我为什么会发生这种情况。或者任何解释同步和异步方法之间差异的博客/文章

最佳答案

您的 getCounter() 方法未同步。因此,即使一个线程可能锁定该方法,另一个线程仍然可以访问并打印您的计数器变量

关于java - 想要一个代码来了解同步方法和异步方法之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10631469/

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