Follow these steps to implement the example:
- Create a class named TaskAtomic and specify that it implements the Runnable interface:
public class TaskAtomic implements Runnable {
- Declare a private AtomicInteger attribute named number:
private final AtomicInteger number;
- Implement the constructor of the class to initialize its attributes:
public TaskAtomic () {
this.number=new AtomicInteger();
}
- Implement the run() method. In a loop with 1,000,000 steps, assign the number of steps to the atomic attribute as a value, using the set() method:
@Override
public void run() {
for (int i=0; i<1000000; i++) {
number.set(i);
}
}
- Create a class named TaskLock and specify that it implements the Runnable interface:
public class TaskLock implements Runnable {
- Declare a private int attribute named number and a private Lock attribute named lock:
private Lock lock;
private int number;
- Implement the constructor of the class to initialize its attributes:
public TaskLock() {
this.lock=new ReentrantLock();
}
- Implement the run() method. In a loop with 1,000,000 steps, assign the number of the steps to the integer attribute. You have to get the lock before the assignment and release it after:
@Override
public void run() {
for (int i=0; i<1000000; i++) {
lock.lock();
number=i;
lock.unlock();
}
}
- Implement the main class of the example by creating a class named Main and adding the main() method to it:
public class Main {
public static void main(String[] args) {
- Create a TaskAtomic object named atomicTask:
TaskAtomic atomicTask=new TaskAtomic();
- Create a TaskLock object named lockTask:
TaskLock lockTask=new TaskLock();
- Declare the number of threads and create an array of Thread objects to store the threads:
int numberThreads=50;
Thread threads[]=new Thread[numberThreads];
Date begin, end;
- Launch the specified number of threads to execute the TaskLock object. Calculate and write its execution time in the console:
begin=new Date();
for (int i=0; i<numberThreads; i++) {
threads[i]=new Thread(lockTask);
threads[i].start();
}
for (int i=0; i<numberThreads; i++) {
try {
threads[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
end=new Date();
System.out.printf("Main: Lock results: %d ",
(end.getTime()-begin.getTime()));
- Launch the specified number of threads to execute the TaskAtomic object. Calculate and write its execution time in the console:
begin=new Date();
for (int i=0; i<numberThreads; i++) {
threads[i]=new Thread(atomicTask);
threads[i].start();
}
for (int i=0; i<numberThreads; i++) {
try {
threads[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
end=new Date();
System.out.printf("Main: Atomic results: %d ",
(end.getTime()-begin.getTime()));