If you need a shared counter in your application which would be accessed by multiple threads then you don't need to re-invent the wheel, AtomicInteger class of concurrent package can help you in that.
Example:
Example:
package com.meritmix.blog.java;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author Ravi Yadav
* This is copyright content of MeritMix.com
* blog address is blog.meritmix.com
*/
public class AtomicIntegerExample {
public static void main(String[] args) {
AtomicInteger counter = new AtomicInteger(0);
for (int i = 0; i < 50; i++) {
Runnable runnable = new WorkerThread(counter);
Thread t = new Thread(runnable);
t.start();
}
}
}
class WorkerThread implements Runnable {
AtomicInteger count = null;
WorkerThread(AtomicInteger counter) {
this.count = counter;
}
public void run() {
int value = this.count.incrementAndGet();
System.out.println(value);
}
}
No comments:
Post a Comment