我试图设置同步方法和不同步方法之间的区别。我试过以下代码
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所以请帮助我为什么会这样..。或任何解释同步方法和异步方法之间区别的博客/文章
发布于 2012-05-17 07:26:28
您的getCounter()方法没有同步。因此,即使一个线程可能正在锁定该方法,另一个线程仍然可以访问并打印您的计数器变量。
发布于 2012-05-17 07:27:31
您的代码不同步getCounter方法,以便getCounter方法可以输出计数器的内部状态。方法上的synchronized(this).同步与相同
发布于 2012-05-17 08:09:01
...如果我在我的Thread.sleep()方法中写keepBusy(),会有什么不同。因为输出在这两种情况下都是完全不同的。
它所做的就是让keepBusy()花费很长的时间,因此它使getCounter()等待了很长时间。
输出的差异是由于同步,这使得getCounter()无法在增量状态中“看到”计数器。
,我的意思是,Thread.sleep()和上面的keepBusy()方法中的what循环在线程调度或锁定方面的区别是什么?
没有关系。
作为记录,如果一个真正的程序有一个像keepBusy()这样的方法在同步的方法或块中睡觉,那就不好了。sleep会导致任何试图在目标对象上同步的其他线程被阻塞.这会降低应用程序的实际并行性。
https://stackoverflow.com/questions/10631469
复制相似问题