不废话 直接上代码
import org.apache.http.annotation.GuardedBy;
import org.apache.http.annotation.ThreadSafe;
/**
*
* @author SKy
* @Date 2017年5月31日 下午1:55:54
*
* @version v1.0
*
*/
@ThreadSafe
public class GuardedByTest {
@GuardedBy("this")
private int value;
public synchronized int getNext() {
return value++;
}
}
package com.sky;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
* @author Sky
* @Date 2017年4月19日 下午3:36:23
*
* @version v1.0
*
*/
public class Test {
public static void main(String[] args) {
Map<String,String> map = new HashMap<String,String>();
GuardedByTest next = new GuardedByTest();
for(int i = 0 ; i < 100 ; i++){
new Thread(new Runnable() {
@Override
public void run() {
String value = next.getNext()+"";
System.out.println("线程1:"+value);
map.put(value, value);
}
}).start();
}
for(int i = 0 ; i < 100 ; i++){
new Thread(new Runnable() {
@Override
public void run() {
String value = next.getNext()+"";
System.out.println("线程2:"+value);
map.put(value, value);
}
}).start();
}
try {
Thread.sleep(1000);
System.out.println(map.size());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
网上说用这个jar
<dependency>
<groupId>net.jcip</groupId>
<artifactId>jcip-annotations</artifactId>
<version>1.0</version>
</dependency>
但是我实在不明白
net.jcip.annotations.ThreadSafe和org.apache.http.annotation.ThreadSafe 有什么区别 两个都是线程安全的注解
用法
1. 类Annotation
3个Annotation描述类的可预期的线程安全保证:
@ThreadSafe:类是线程安全的;
@Immutable:类是不可变的(属性为final),不可变对象是线程安全的;
@NotThreadSafe:类不是线程安全的,如果类未加任何注解,则不能确定是否线程安全,认为是非线程安全的。
2. 域Annotation和方法Annotation
描述哪个状态变量被哪个锁保护着,以及哪个锁保护这些变量的信息:
@GuardedBy(lock):线程只有在持有了一个特定的锁(lock)后,才能访问某个域或方法;
@GuardedBy("this"):包换在对象中的内部锁(方法或域是这个对象的一个成员);
@GuardedBy("fieldName"):值与filedName引用的对象相关联的锁,或者是一个隐式锁(filedName没有引用一个Lock),或者是一个显示锁(filedName引用了一个Lock);
@GuardedBy("ClassName.fieldName"):类似于@GuardedBy("fieldName"),不过所引用的锁对象是存储在另一个类(或本类)中的静态域;
@GuardedBy("methodName()"):锁对象是methodName()方法的返回值;
@GuardedBy("ClassName.class"):ClassName类的直接量对象。