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

# AtomicIntegerExample

The document presents a Java program that demonstrates the use of AtomicInteger for thread-safe incrementing and decrementing operations. It includes a Producer thread that increments the AtomicInteger and a Consumer thread that decrements it. The final result is printed after both threads complete their execution.

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

# AtomicIntegerExample

The document presents a Java program that demonstrates the use of AtomicInteger for thread-safe incrementing and decrementing operations. It includes a Producer thread that increments the AtomicInteger and a Consumer thread that decrements it. The final result is printed after both threads complete their execution.

Uploaded by

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

# AtomicIntegerExample

import java.util.concurrent.atomic.*;

public class AtomicIntegerExample {

public static void main(String[] args) {


AtomicInteger atmint = new AtomicInteger(0);

Thread producer = new Thread(new Producer(atmint));


Thread consumer = new Thread(new Consumer(atmint));

producer.start();
consumer.start();
try {
producer.join();
consumer.join();
} catch (InterruptedException s) {}
System.out.println("result: atmint="+atmint.get());
}
}

class Producer implements Runnable{

private AtomicInteger atm;

public Producer(AtomicInteger atmval) {


this.atm = atmval;
}

public void run() {

for (int i = 0; i < 10000002; i++) {


atm.incrementAndGet(); // atm++;
}
}
}

class Consumer implements Runnable{

private AtomicInteger atm;

public Consumer(AtomicInteger atmval) {


this.atm = atmval;
}

public void run() {


for (int i = 0; i < 10000000; i++) {
atm.decrementAndGet(); // atm--;
}
}
}

You might also like