1

I have two methods in two different classes, like this

public class ClassX implements Runnable {

    public  void methodAandB() {
        for(int i=0;i<10;i++) {
            System.out.println("This is A and B ");
        }
    }
    @Override
    public void run() {
        methodAandB();
    }
}

public class ClassY implements Runnable {

    public void methodAorB() {
        for(int i=0;i<10;i++) {
            System.out.println("This is A or B");
        }
    }

    @Override
    public void run() {
        methodAorB(a);
    }
}

Thread t1 is calling methodAandB().

Thread t2 is calling methodAorB().


Can I switch between these two threads after each iteration of loop in methods?

I want to get output like this:

This is A and B

This is A or B

This is A and B

This is A or B

This is A and B

This is A or B

This is A and B

This is A or B

3
  • 3
    Why would you want to do that? If you only want to do one thing at a time, use a single thread. The point of separate threads is to allow parallel mostly-independent execution. There are certainly ways of achieving this sort of synchronization, but it often (not always) suggests that threads shouldn't be used to start with.
    – Jon Skeet
    Mar 20, 2013 at 17:25
  • 1
    Are you sure you want to use threads? You can do what you want with locks but it's defeating the purpose of having threads. Actually the way you want will require so much locking and switching between threads that it would be faster with one thread.
    – andre
    Mar 20, 2013 at 17:27
  • You could accomplish what you want with a shared wait condition between the 2 threads but I agree with the above.. no need for threads here. Mar 20, 2013 at 17:32

5 Answers 5

2

Best example of flip-flop between threads:

Given two int array (even and odd), 2 threads printing their numbers in natural order.

package com.rough;

public class ThreadsBehaviour {

    static Object lock = new Object();

    public static void main(String[] args) throws InterruptedException {

        int a[] = {1,3,5,7,9};
        int b[] = {2,4,6,8,10};

        Thread odd = new Thread(new Looper(a, lock));
        Thread even = new Thread(new Looper(b, lock));

        odd.start();
        even.start();
    }

}

class Looper implements Runnable
{

    int a[];
    Object lock;

    public Looper(int a[], Object lock)
    {
        this.a = a;
        this.lock = lock;
    }
    @Override
    public void run() {

        for(int i = 0; i < a.length; i++)
        {
            synchronized(lock)
            {

                System.out.print(a[i]);
                try 
                {
                    lock.notify();
                    if(i == (a.length - 1))
                    {
                        break;
                    }
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

    }

}
2

You can achieve this simply by using the shared variables. I have implemented and verified the problem. code is below

class X

public class ClassX implements Runnable {
public  void methodAandB() {
    for(int i=0;i<10;i++) {
        while(GlobalClass.isClassXdone)
        {}
        System.out.println("This is A and B ");
        GlobalClass.isClassXdone = true;
        GlobalClass.isClassYdone = false;
}}
@Override
public void run() {
    methodAandB(); } }

ClassY

public class ClassY implements Runnable {
public  void methodAorB() {
    for(int i=0;i<10;i++) {
         while(GlobalClass.isClassYdone)
         {}
        System.out.println("This is A or B ");
        GlobalClass.isClassYdone = true;
        GlobalClass.isClassXdone = false;}}
@Override
public void run() {
    methodAorB();}}

Definition of the shared variable

public class GlobalClass {

public  static boolean isClassXdone = false ;
public  static boolean isClassYdone = false ;
}

You can just start your thread using t1.start and t2.start to get the desired output

    Thread t1 = new Thread(new ClassX());
    Thread t2 = new Thread(new ClassY());
    t1.start();
    t2.start();
0

This is probably more than needed to solve the problem, but, as it seems to be an introduction to concurrent programming exercise, it should be along the lines of what you'll encounter.

You should probably have a shared object that both your threads know, so that they may synchronize through it. Like so:

public class MyMutex {
    private int whoGoes;
    private int howMany;

    public MyMutex(int first, int max) {
        whoGoes = first;
        howMany = max;
    }

    public synchronized int getWhoGoes() { return whoGoes; }

    public synchronized void switchTurns() {
        whoGoes = (whoGoes + 1) % howMany;
        notifyAll();
    }

    public synchronized void waitForMyTurn(int id) throws
            InterruptedException {
        while (whoGoes != id) { wait(); }
    }
}


Now, your classes should receive their respective identifier, and this shared object.

public class ClassX implements Runnable {
    private final int MY_ID;
    private final MyMutex MUTEX;

    public ClassX(int id, MyMutex mutex) {
        MY_ID = id;
        MUTEX = mutex;
    }

    public void methodAandB() {
        for(int i = 0; i < 10; i++) {
            try {
                MUTEX.waitForMyTurn(MY_ID);
                System.out.println("This is A and B ");
                MUTEX.switchTurns();
            } catch (InterruptedException ex) {
                // Handle it...
            }
        }
    }
    @Override
    public void run() { methodAandB(); }
}

ClassY should do the same. Wait for its turn, do its action, and then yield the turn to the other.

0

I know it's a little late to answer this. But it's yesterday only I have come across this question. So I guess it's never too late.. ;)

Solution, as @afsantos mentioned is having a shared object between the two threads and implementing mutual exclusion on the shared object. The shared object could be alternatively locked by the two threads. Two possible implementations are as follows. This is actually more like an extension of @afsantos solution. His work is hereby acknowledged.

Solution 1: Blueprint of the object that will be shared is as follows.

public class MutEx {
    public int whoGoes, howMany;

    public MutEx(int whoGoes, int howMany) {
        this.whoGoes = whoGoes;
        this.howMany = howMany;
    }

    public synchronized void switchTurns(){
        this.whoGoes = (this.whoGoes + 1) % 2;
        notifyAll();
    }

    public synchronized void waitForTurn(int id) throws InterruptedException{
        while(this.whoGoes != id)
            wait();
    }
}

Then, you could implement the ClassX as follows.

public class ClassX implements Runnable {
    private final int MY_ID;
    private final MutEx MUT_EX;

    public ThreadOne(int MY_ID, MutEx MUT_EX) {
        this.MY_ID = MY_ID;
        this.MUT_EX = MUT_EX;
    }

    @Override
    public void run(){
        this.doTheWork();
    }

    public void doTheWork(){
        for(int i = 0; i < 10; i++){
            try {
                MUT_EX.waitForMyTurn(MY_ID);
                System.out.println("This is A and B");
                MUT_EX.switchTurns();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

ClassY also will be the same, with whatever the differences you need to be there. Then, in the invocation (i.e. in the main method),

public static void main(String[] args) {
    MutEx mutEx = new MutEx(0, 2);
    Thread t1 = new Thread(new ClassX(0, mutEx);
    Thread t2 = new Thread(new ClassY(1, mutEx));
    t1.start();
    t2.start();
}

Voila! You have two threads, alternating between each as you need.

Solution 2: Alternatively, you could implement the ClassX & ClassY as follows.

public class ClassX extends Thread{

Here, you are subclassing the java.lang.Thread to implement your requirement. For this to be invoked, change the main method as follows.

public static void main(String[] args) {
    MutEx mutEx = new MutEx(0, 2);
    ClassX t1 = new ClassX(0, mutEx);
    ClassY t2 = new ClassY(1, mutEx);
    t1.start();
    t2.start();
}

Run this, and you have the same result.

-3

If you don't need to use Thread try this code:

for (int i = 0; i < 20; i++) {
    if (i % 2 == 0) {
        methodAandB();
    } else {
        methodAorB();
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.