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