0

I want to make Opposite Thread in java.

If Thread A is running, then Thread B is waiting. The other way, Thread B is running, then Thread A is waiting.

A : -----       ------------------     -----------

B :    ------------          --------

I want to write code with wait(), notify function(not suspend(), resume) But it is very difficult for me.

Help me

Edi G.
  • 2,432
  • 7
  • 24
  • 33
MrLee
  • 31
  • 3
  • ok.. where are you stucked? What do you think is difficult? Did you tried solving? – SMA Mar 10 '15 at 07:09
  • 2
    possible duplicate of [Printing Even and Odd using two Threads in Java](http://stackoverflow.com/questions/16689449/printing-even-and-odd-using-two-threads-in-java) – Kedar Parikh Mar 10 '15 at 07:12
  • Documentation is your friend - start with the [Java Concurrency Tutorial](http://docs.oracle.com/javase/tutorial/essential/concurrency/), and try experiments with some code. It'll work a lot better than us trying to explain these concepts to you in a very broad question like this. Come back if you have a specific question based on what you learn. – Krease Mar 10 '15 at 07:15
  • Even difficult for me, until I actually code it ! – Neeraj Jain Mar 10 '15 at 08:17

1 Answers1

0

You need to synchronize on two variables.

public class T1 implements Runnable {
    public static final Object LOCK = new Object();  

    public void run() {
        try {
            while (true) {
                // Your code here
                T2.LOCK.notify();
                T1.LOCK.wait();
            }
        } catch (Exception e) {
            // Handle exception
        }
    }
}

public class T2 implements Runnable {
    public static final Object LOCK = new Object();

    public void run() {
        try {
            T2.LOCK.wait();
            while (true) {
            // Your code here
                T1.LOCK.notify();
                T2.LOCK.wait();
            }
        } catch (Exception e) {
            // Handle exception
        }
    }
}
Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56