How to switch between two thread back and forth

Bhanu_Jain picture Bhanu_Jain · Mar 20, 2013 · Viewed 11.5k times · Source

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

Answer

Count picture Count · May 13, 2014

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();