Nul*_*ion 2 java multithreading
我试图设置同步和非同步方法之间的区别..我试过以下代码
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");
}
}
Run Code Online (Sandbox Code Playgroud)
所以上面我有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
Run Code Online (Sandbox Code Playgroud)
所以,请帮助我为什么会发生这种情况..或者任何博客/文章,用于解释同步和异步方法之间的区别
| 归档时间: |
|
| 查看次数: |
1487 次 |
| 最近记录: |