1

I got it interview that:

Thread-A Prints Even numbers from 0
Thread-B prints Odd numbers from 1

I want to print 0 1 2 3 4.... in natural order till 1000 How can I achive.

I tried this way:

public class ThreadDemo2 {
    static int aa = 0;

    public static void main(String[] args) {
        boolean mytime = true;
        EvenThread et = new EvenThread(mytime);
        OddThread ot = new OddThread(mytime);
        et.start();
        ot.start();

    }

}

class EvenThread extends Thread {
    boolean mytime;
    int i = 0;

    public EvenThread(boolean mytime) {
        this.mytime = mytime;
    }

    public void run() {
        //if (ThreadDemo2.aa == 0) {
            for (int i = 0; i < 1000 && ThreadDemo2.aa == 0; i += 2) {
                System.out.println(i);
                ThreadDemo2.aa = 1;
                try {
                    sleep(500);

                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
        //  }

        }/* else
            try {
                this.wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }*/
    }

}

class OddThread extends Thread {
    boolean mytime;
    int i = 1;

    public OddThread(boolean mytime) {
        this.mytime = mytime;
    }

    public void run() {
        //if (ThreadDemo2.aa == 1) {
            for (int i = 1; i < 1000 && ThreadDemo2.aa == 1; i += 2) {
                System.out.println(i);
                ThreadDemo2.aa = 0;
                try {
                    sleep(500);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            //ThreadDemo2.aa = 0;
        //}
    }

}
Sun
  • 3,444
  • 7
  • 53
  • 83
  • Do not expect others to copy your code, compile and run it. It is easier if you tell us what happens. Besides, as far as I can say, your code is lacking the essential thing that is required here: you have to interlock the two threads, basically they need to run in lockstep in order to print the numbers in the correct order. Thats like the **hard** part of the assignment. So, you want us to do the heavy lifting for you? – GhostCat Mar 23 '16 at 12:24
  • @Jägermeister, that is the opposite of what we usually tell people. You want the OP to "tell you what happens," but the OP does not _understand_ what happens. That's why he's asking. There is no better description of what code actually does than the code itself. Just try counting the comments on SO that say, "Dude! Show us your code!" OTOH, some times they post too much code, and we ask them to simplify it: (see http://sscce.org/) – Solomon Slow Mar 23 '16 at 14:08
  • Please see: http://stackoverflow.com/a/36183057/437506 for another take. – Kedar Mhaswade Mar 23 '16 at 16:03

4 Answers4

0

When you start the threads, at that time, ThreadDemo2.aa = 0.

So, the for loop in OddThread never starts. Hence the program does not move forward.

Instead:

  • remove the condition && ThreadDemo2.aa == 0//or 1 from both the for loops.
  • remove the time delay.
  • add this line: while(ThreadDemo2.aa == 0){}// or 1 in the respective loops.

This line will make the for loop wait, till the value is correct, and then only the loop moves forward. This should solve your problem.

dryairship
  • 6,022
  • 4
  • 28
  • 54
0

Unfortunately you can't expect the result because of JVM working on 2 different threads , but you can do something like that,

public class Test12 {

public static void main(String[] args) {
    Thread1 t1=new Thread1();
    Thread2 t2=new Thread2();


}

}

class Thread1 implements Runnable {

public Thread1() {
    Thread t = new Thread();
    t.start();
}

@Override
public void run() {
    try {
        for (int i = 0; i < 1000; i++) {
            if (i % 2 == 0) {
                System.out.println(i);
            }

        }

    } catch (Exception e) {

    }
}
}

class Thread2 implements Runnable {

public Thread2() {
    Thread t = new Thread(this);
    t.start();

}

@Override
public void run() {
    try {
        for (int i = 0; i < 1000; i++) {
            if (i % 2 == 1) {
                System.out.println(i);
            }

        }

    } catch (Exception e) {

    }
}

}

when you run this application many times, you will notice that there are no result like other 100%

Basil Battikhi
  • 2,638
  • 1
  • 18
  • 34
  • thanks, it working will, I am able to understand the code. but It not working will if i change 1000 to 10. – Sun Mar 23 '16 at 16:01
  • I told you you cant expect the result so there are no result like other 100% it depends on OS or your JVM im not sure – Basil Battikhi Mar 23 '16 at 16:06
0

This approach lets you perform your task. Using monitors, you will not need to add extra loops to ensure the correct output.

public class ThreadDemo2 {
    static int aa = 0;
    static Object lock = new Object();

    public static void toggleThread(int threadaa) throws Exception
    {
    synchronized(lock)
    {
        if(aa == threadaa)
        {
            aa = (threadaa - 1) * -1;
            lock.notifyAll();
            lock.wait();
        }
        else
        {
            lock.wait();
        }
    }
    }

    public static void releaseThreads()
    {
    try
    {
            synchronized(lock)
        {
            lock.notifyAll();
        }
    }
    catch(Exception e)
    {
    }
    }

    public static void main(String[] args) {
        boolean mytime = true;
        EvenThread et = new EvenThread(mytime);
        OddThread ot = new OddThread(mytime);
        et.start();
        ot.start();

    }

}

class EvenThread extends Thread {
    boolean mytime;
    int i = 0;

    public EvenThread(boolean mytime) {
        this.mytime = mytime;
    }

    public void run() {
        //if (ThreadDemo2.aa == 0) {
            for (int i = 0; i < 10; i += 2) {       
                try {
                    ThreadDemo2.toggleThread(0);

                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
        System.out.println(i);
        //  }

        }/* else
            try {
                this.wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }*/
    ThreadDemo2.releaseThreads();
    }

}

class OddThread extends Thread {
    boolean mytime;
    int i = 1;

    public OddThread(boolean mytime) {
        this.mytime = mytime;
    }

    public void run() {
        //if (ThreadDemo2.aa == 1) {
            for (int i = 1; i < 10; i += 2) {


                try {
                    ThreadDemo2.toggleThread(1);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
        System.out.println(i);
            }
            //ThreadDemo2.aa = 0;
        //}
    ThreadDemo2.releaseThreads();
    }

}
Nadir
  • 1,799
  • 12
  • 20
0

Probably the scope of your exercise was to use Thread locks. The below example uses two Monitor Object locks. Each of the threads basically waits for the other to complete its iteration before moving forward.

public class ThreadInterleave {

    public static class Even implements Runnable{
        private Object even;
        private Object odd;
        private int count = 0;

        public Even(Object even,Object odd){
            this.even = even;
            this.odd = odd;
        }

        public void run(){
            while(count<1000) {
                    System.out.println(count);
                    count+=2;
                synchronized (odd){
                    odd.notify();
                }

                synchronized (even){
                    try {
                        even.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }



            }
        }
    }

    public static class Odd implements Runnable{
        private Object even;
        private Object odd;
        private int count = 1;

        public Odd(Object even,Object odd){
            this.even = even;
            this.odd = odd;
        }

        public void run(){
            while(count<1000) {
                System.out.println(count);
                count+=2;
                synchronized (even){
                    even.notify();
                }

                synchronized (odd){
                    try {
                        odd.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }



            }
        }
    }

public static void main(String[] args){
        final Object even = new Object();
        final Object odd = new Object();
        Thread tEven = new Thread(new Even(even,odd));
        Thread tOdd = new Thread(new Odd(even,odd));


        tEven.start();
        tOdd.start();



    }
}
Radu Ionescu
  • 3,462
  • 5
  • 24
  • 43