Lokesh Lokesh - 1 year ago 556
Java Question

3 threads to print alternate values in sequence

I am trying to create an implementation where multiple threads print alternate values of sequence. So here thread1 will print 1,4,7 thread2 will print 2,5,8 thread3 will print 3,6,9. I am using Atomic integer and modulo function.

Below implementation works fine in the sense that first thread prints 1,4,7 while second prints 2,5,8 and third prints 3,6,9 but problem is that sequence is not maintained i.e output can be like 1,3,2,4,5,7,8,6,9 while i want sequence to be maintained as proper threads shld print those values.
One condition is i don't want to use synchronize. [Just for learning purpose]

import java.util.concurrent.atomic.AtomicInteger;

public class ThreeThreadsOrderedLockLess {

AtomicInteger sharedOutput = new AtomicInteger(0);

public static void main(String args[]) {

ThreeThreadsOrderedLockLess t = new ThreeThreadsOrderedLockLess();

ThreadTasks t1 = t.new ThreadTasks(0);
ThreadTasks t2 = t.new ThreadTasks(1);
ThreadTasks t3 = t.new ThreadTasks(2);

Thread ts1 = new Thread(t1);
Thread ts2 = new Thread(t2);
Thread ts3 = new Thread(t3);


private class ThreadTasks implements Runnable {

private final int threadPosition;

public ThreadTasks(int threadPosition) {

this.threadPosition = threadPosition;

public void run() {

while (sharedOutput.get() < 9) {

if (sharedOutput.get() % 3 == this.threadPosition) {

System.out.println("Printing output for Thread: "
+ this.threadPosition + " "
+ sharedOutput.incrementAndGet());



Answer Source

You should print first, and increment after:

int value = sharedOutput.get() + 1;
System.out.println("Printing output for Thread: "
                        + this.threadPosition + "  "
                        + value);

That said, all the threads are busy looping, which will lead to 100% CPU usage. You should synchronize the threads instead.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download