ThreadTest.java:java
package main; import java.util.concurrent.atomic.AtomicLong; import net.jcip.annotations.GuardedBy; import net.jcip.annotations.ThreadSafe; @ThreadSafe public class ThreadTest { private long hits1; @GuardedBy("this") private long hits2; private final AtomicLong count = new AtomicLong(0); public long getCounts() { return count.get(); } public synchronized long getHits1() { return hits1; } public synchronized long getHits2() { return hits2; } public synchronized void IncreaseHits1() { ++hits1; } public void service(int n) throws InterruptedException { for (int i = 1; i <= n; i++) { new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub synchronized (this) { ++hits2; } IncreaseHits1(); count.incrementAndGet(); } }).start(); } System.err.println("All Threads running!"); Thread.currentThread().sleep(2000); System.out.println("hits1:" + getHits1() + " hits2:" + getHits2() + " AtomicLong:" + getCounts()); } }
main.java:安全
package main; public class main { public static void main(String[] args) throws InterruptedException { ThreadTest threadTest = new ThreadTest(); for (int i = 0; i < 1000; i++) { threadTest.service(10000); } } }
請問,hits2是否最後的結果是否正確,是否線程安全?
ide
當累計跑了185次service後,控制檯輸出爲:this
synchronized (this) { ++hits2; }
看輸出結果的話,上面這這一小段同步塊代碼貌似並不是是線程安全的。不瞭解java註解有什麼做用如@ThreadSafe和@GuardedBy("this"),應該不會對運行結果形成什麼影響吧。atom