我正在嘗試使用與Atomic變量(java.util.concurrent.atomic包)比較的方法使用同步的Java多線程。java在方法上同步不工作?
下面是類:從運行的是原子
// Interface ICounter.java
public interface ICounter {
public void increment();
public void decrement();
public int value();
}
// Class Counter.java
public class Counter implements ICounter {
private int c = 0;
@Override
public void increment() {
c++;
}
@Override
public void decrement() {
c--;
}
@Override
public int value() {
return c;
}
}
// Class AtomicCounter.java
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicCounter implements ICounter {
private AtomicInteger c = new AtomicInteger(0);
@Override
public void increment() {
c.incrementAndGet();
}
@Override
public void decrement() {
c.decrementAndGet();
}
@Override
public int value() {
return c.get();
}
public long getIncrement() {
return c.incrementAndGet();
}
}
// Class MainProg.java
public class MainProg {
public static void main(String args[]) {
ICounter counter = new AtomicCounter();
//ICounter counter = new SynchronizedCounter();
Thread thread1 = new Thread(new CountRunner(counter));
Thread thread2 = new Thread(new CountRunner(counter));
thread1.start();
thread2.start();
}
}
class CountRunner implements Runnable {
private ICounter counter;
public CountRunner(ICounter counter) {
this.counter = counter;
}
public void run() {
while (true) {
counter.increment();
System.out.println(Thread.currentThread().getName() + " count=" + counter.value());
System.out.println("-------------------");
try {
Thread.sleep(2000L);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
結果或同步不表明變量整數是線程安全的,例如:
Thread-0 count=1
-------------------
Thread-1 count=2
-------------------
Thread-0 count=3
-------------------
Thread-1 count=4
-------------------
Thread-0 count=5
-------------------
Thread-1 count=6
-------------------
Thread-0 count=7
-------------------
Thread-1 count=8
-------------------
Thread-0 count=10
-------------------
Thread-1 count=10
-------------------
從結果來看,最後2行顯示2個線程正在訪問計數器類的整數變量的相同值。 也許我在這裏失去了一些東西?
謝謝!