前面說到了Java中的同步問題
public class Counter {
private int c =
public void increment() {
System
c++;
try {
Thread
} catch (InterruptedException e) {
e
}
System
}
public void decrement() {
System
c
try {
Thread
} catch (InterruptedException e) {
e
}
System
}
public int value() {
return c;
}
}
在上面的Counter類的實現中
下面是兩個線程
Thread
public class ThreadA implements Runnable {
private Counter c;
public ThreadA(Counter c) {
this
}
@Override
public void run() {
for (int i =
this
}
}
}
ThreadB
public class ThreadB implements Runnable {
private Counter c;
public ThreadB(Counter c) {
this
}
@Override
public void run() {
for (int i =
this
}
}
}
主程序如下
public class Main {
public static void main(String[] args) {
Counter c = new Counter();
ThreadA a = new ThreadA(c);
ThreadB b = new ThreadB(c);
Thread threadA = new Thread(a);
Thread threadB = new Thread(b);
threadA
threadB
}
}
執行上面的代碼
before increment
before decrement
after increment
before increment
after decrement
before decrement
after increment
before increment
after decrement
before decrement
after increment
before increment
after decrement
before decrement
after increment
before increment
after decrement
before decrement
after increment
before increment
after decrement
before decrement
after increment
before increment
after increment
before increment
after decrement
before decrement
after decrement
before decrement
after increment
before increment
after increment
before increment
after decrement
before decrement
after increment
after decrement
before decrement
after decrement
從上面的輸出結果中我們不難看出出現了嚴重的交錯現象! 在increment或者是decrement方法中輸出before和after本應該是成對連續出現的
將上面代碼的increment()和decrement()方法用synchronized 修飾後
before increment
after increment
before increment
after increment
before decrement
after decrement
before increment
after increment
before decrement
after decrement
before decrement
after decrement
before decrement
after decrement
before decrement
after decrement
before increment
after increment
before decrement
after decrement
before decrement
after decrement
before decrement
after decrement
before decrement
after decrement
before increment
after increment
before decrement
after decrement
before increment
after increment
before increment
after increment
before increment
after increment
before increment
after increment
before increment
after increment
這樣輸出結果和沒有增加synchronized修飾符時的大不相同
至少
另外
From:http://tw.wingwit.com/Article/program/Java/hx/201311/26369.html