| Refresh | Home EGTry.com

generate a unique id in JVM instance using AtomicLong


output

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

sample counter code

package 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());
		}
	}
}