0% found this document useful (0 votes)
2 views

# AtomicTest.java

The document contains a Java program that demonstrates the use of AtomicInteger for thread-safe incrementing and decrementing operations. It creates two threads, a Producer that increments an atomic integer and a Consumer that decrements it, while measuring the execution time. The program outputs the final value of the atomic integer and the time taken for the operations.

Uploaded by

hoangtu112201
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

# AtomicTest.java

The document contains a Java program that demonstrates the use of AtomicInteger for thread-safe incrementing and decrementing operations. It creates two threads, a Producer that increments an atomic integer and a Consumer that decrements it, while measuring the execution time. The program outputs the final value of the atomic integer and the time taken for the operations.

Uploaded by

hoangtu112201
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

# AtomicTest.

java
import java.util.concurrent.atomic.*;

public class AtomicTest {

public static void main(String[] args) {


AtomicInteger atomic_int = new AtomicInteger(0);
int inc_num = 10001234;
int dec_num = 10000000;

long start = System.currentTimeMillis();


Thread p = new Thread (new Producer(atomic_int, inc_num));
p.start();
Thread c = new Thread (new Consumer(atomic_int, dec_num));
c.start();
try {
p.join();
} catch (InterruptedException e) {}

try {
c.join();
} catch (InterruptedException e) {}
long finish = System.currentTimeMillis();
System.out.println(inc_num+" inc() calls, "+dec_num+" dec() calls = " +
atomic_int.get());
System.out.println("With-Atomic Time: "+(finish-start)+"ms");
}
}

class Producer implements Runnable{


private AtomicInteger myAtomicCounter;
int num;

public Producer(AtomicInteger x, int Num) {


this.num=Num;
this.myAtomicCounter = x;
}

@Override
public void run() {
for (int i = 0; i < num; i++) {
myAtomicCounter.incrementAndGet(); // myAtomicCounter++
}
}
}

class Consumer implements Runnable{

private AtomicInteger myAtomicCounter;


int num;

public Consumer(AtomicInteger x, int Num) {


this.num=Num;
this.myAtomicCounter = x;
}

@Override
public void run() {
for (int i = 0; i < num; i++) {
myAtomicCounter.decrementAndGet(); // myAtomicCounter--
}
}
}

You might also like