| Refresh | Home EGTry.com

counter read/write by multiple threads


AtomicCounter.java

package egtry.thread;

import java.util.concurrent.atomic.AtomicLong;

public class AtomicCounter extends Thread {

	private static AtomicLong counter=new AtomicLong(10);

	public static void main(String[] args) throws Exception {
		AtomicCounter thread1=new AtomicCounter();
		thread1.start();
		AtomicCounter thread2=new AtomicCounter();
		thread2.start();
		AtomicCounter thread3=new AtomicCounter();
		thread3.start();
	
	}

	@Override
	public void run() {
		
		Thread t=Thread.currentThread();
		long id=t.getId();
		
		for(long i=0; i<10; i++) {
			long nextLong=counter.incrementAndGet();
			System.out.println(nextLong +"\t"+id);
			Sleep(10); 
		}
			
	}
	
	public static void Sleep(int ms) {
		try {
			Thread.sleep(ms);
			} catch (Exception e) {
				System.out.println(e.getMessage());
		}
	}
}


Output

11	8
12	9
13	10
14	8
15	9
16	10
17	8
18	9
19	10
20	9
21	8
22	10
23	8
24	9
25	10
26	8
27	9
28	10
29	8
30	9
31	10
32	9
33	8
34	10
35	8
36	9
37	10
38	9
39	8
40	10