线程安全的概念

    1. 线程安全的类

    一个类是否是线程安全的,主要看这个类在多线程中是否能被安全的使用。

    2. 线程安全的例子

 

@ThreadSafe
public class StatelessFactorizer implements Servlet {
    public void service(ServletRequest req, ServletResponse resp) {
        BigInteger i = extractFromRequest(req);
        BigInteger[] factors = factor(i);
        encodeIntoResponse(resp, factors);
    }
}

 

   对于上面的代码,因为两个线程并没有共享的数据,所以线程之前不会相互影响。上面的代码总是线程安全的。

   3. 非线程安全的类

 

@NotThreadSafe
public class UnsafeCountingFactorizer implements Servlet {
    private long count = 0;

    public long getCount() { return count; }

    public void service(ServletRequest req, ServletResponse resp) {
        BigInteger i = extractFromRequest(req);
        BigInteger[] factors = factor(i);
        ++count;
        encodeIntoResponse(resp, factors);
    }

你可能感兴趣的:(线程安全)