0% found this document useful (0 votes)
17 views2 pages

# 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
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views2 pages

# 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
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

# AtomicTest.

java
import [Link].*;

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 = [Link]();


Thread p = new Thread (new Producer(atomic_int, inc_num));
[Link]();
Thread c = new Thread (new Consumer(atomic_int, dec_num));
[Link]();
try {
[Link]();
} catch (InterruptedException e) {}

try {
[Link]();
} catch (InterruptedException e) {}
long finish = [Link]();
[Link](inc_num+" inc() calls, "+dec_num+" dec() calls = " +
atomic_int.get());
[Link]("With-Atomic Time: "+(finish-start)+"ms");
}
}

class Producer implements Runnable{


private AtomicInteger myAtomicCounter;
int num;

public Producer(AtomicInteger x, int Num) {


[Link]=Num;
[Link] = x;
}

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

class Consumer implements Runnable{

private AtomicInteger myAtomicCounter;


int num;

public Consumer(AtomicInteger x, int Num) {


[Link]=Num;
[Link] = x;
}

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

You might also like