Hi,

I have two threads A and B. Thread A prints only odd numbers. Thread B prints only even number. I want to synchronize it in such a way that on the screen I get continues numbers. How can I do that?
I was thinking of using sockets. Thread A prints and sends a message to thread B. Thread B prints and then sends a message to thread A. Any thread before printing checks for the message from other thread and prints only if they have received the message.

Is this the best design or any of you have a better design?

Thank-you in advance,
Sri

Dani AI

Generated

Short answer: don’t use sockets — use a synchronization primitive and a shared counter. Sockets are heavy and add I/O latency; simple thread primitives (semaphores, condition variables or a Lock+Condition) do the job with far less complexity.

Here is a compact, safe Java example using two Semaphores and an AtomicInteger. odd starts with a permit so printing begins at 1; each printer acquires its semaphore, prints one number, increments the shared counter, then releases the other semaphore. The threads check a MAX and release the partner before exiting so no thread is left blocked.

import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;

final int MAX = 100;
AtomicInteger counter = new AtomicInteger(1);
Semaphore odd = new Semaphore(1);   // allow odd thread to go first
Semaphore even = new Semaphore(0);

Runnable oddPrinter = () -> {
  while (true) {
    odd.acquireUninterruptibly();
    int n = counter.get();
    if (n > MAX) { even.release(); break; }
    System.out.println(n);           // odd
    counter.incrementAndGet();
    even.release();
  }
};

Runnable evenPrinter = () -> {
  while (true) {
    even.acquireUninterruptibly();
    int n = counter.get();
    if (n > MAX) { odd.release(); break; }
    System.out.println(n);           // even
    counter.incrementAndGet();
    odd.release();
  }
};

new Thread(oddPrinter).start();
new Thread(evenPrinter).start();

Troubleshooting and notes:

  • is right: avoid sockets for thread signalling. ’s hint toward wait/notify is valid too, but if you use wait/notify or Condition, always wait inside a loop to handle spurious wakeups.
  • Use AtomicInteger (or synchronized access) so increments are visible and atomic between threads.
  • To avoid starvation or ordering surprises, consider a fair Semaphore (new Semaphore(1, true)) if fairness matters.
  • Console printing is slow; for high throughput use a buffer or collect results then print.
  • Same pattern translates to other languages: two semaphores or a pair of condition variables plus a shared counter will produce the continuous sequence cleanly.

Recommended Answers

All 3 Replies

If you understand the synchronization it is about locking a resource which can be used by a thread at a time but does not control the behaviour of a thread completely in this case we can make use of functions which are used to wait & notify other threads. If you follow this approach hope it will help you

I was thinking of using sockets. Thread A prints and sends a message to thread B. Thread B prints and then sends a message to thread A. Any thread before printing checks for the message from other thread and prints only if they have received the message.

You have the right idea, but the wrong channel of communication. Communicating thread notifications through a socket is terrible from a performance point of view. All operating systems or multi-threading frameworks will provide a number of different types of thread synchronization mechanism to do this kind of thing. There are a number of approaches that could solve your problem. One solution is a condition variable which basically allows one thread to notify another of a condition. Another is a synchronization barrier which allows two threads to have a "meeting point" that both must reach before any one of them can continue. You could probably also solve your problem with a pair of mutex locks, but be wary of dead-locks. For faster operations, you can also use atomic operations on volatile flags. I think that's enough food for thoughts.

Thread A prints and sends a message to thread B. Thread B prints and then sends a message to thread A. Any thread before printing checks for the message from other thread and prints only if they have received the message.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.