william
william

Reputation: 39

why this thread is not safe

Example One:

public class Test { 
        public static void main(String[] args) { 
                ExecutorService pool = Executors.newFixedThreadPool(2); 
                Runnable t1 = new MyRunnable("A", 2000); 
                Runnable t2 = new MyRunnable("B", 3600); 
                Runnable t3 = new MyRunnable("C", 2700); 
                Runnable t4 = new MyRunnable("D", 600); 
                Runnable t5 = new MyRunnable("E", 1300); 
                Runnable t6 = new MyRunnable("F", 800); 

                pool.execute(t1); 
                pool.execute(t2); 
                pool.execute(t3); 
                pool.execute(t4); 
                pool.execute(t5); 
                pool.execute(t6); 

                pool.shutdown(); 
        } 
} 

class MyRunnable implements Runnable { 
        private static AtomicLong aLong = new AtomicLong(10000);   
        private String name;             
        private int x;                       

        MyRunnable(String name, int x) { 
                this.name = name; 
                this.x = x; 
        } 

        public void run() { 
                System.out.println(name + " excute" + x + ",money:" + aLong.addAndGet(x)); 
        } 
}

this thread is not safe in this sample.

Example Two

public class CountingFactorizer implements Servlet { 
    private final AtomicLong count = new AtomicLong(0); 

    public void service(ServletRequest req, ServletResponse resp) { 
        count.incrementAndGet(); 
    } 
}

why is this thread safe? somebody can tell me?

I'm study thread in java, but cannot understand two sample. Are they different?

Upvotes: 0

Views: 80

Answers (1)

Filippo Fratoni
Filippo Fratoni

Reputation: 389

As far I can see both are thread safe. In both examples the static, class level, member is AtomicLong that is thread safe by definition. All other members in the first example are instance level member and are executed in different threads, so no conflicts at all.

Upvotes: 1

Related Questions