Java 同步代碼塊的疑問

ThreadTest.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是否最後的結果是否正確,是否線程安全?

當累計跑了185次service後,控制檯輸出爲:

wKioL1N96FXDPN20AAF1dq37do0409.jpg


synchronized (this) {
    ++hits2;
}

看輸出結果的話,上面這這一小段同步塊代碼貌似並非是線程安全的。不瞭解java註解有什麼作用如@ThreadSafe和@GuardedBy("this"),應該不會對運行結果造成什麼影響吧。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章