Search code examples
javamultithreadingrunnable

How come implements runnable always interweaves the results?


Going off my last question on threads , Why my input is showing one thread executing after another thread, not at the same time?, I received answers like "In case of Multi-threading there is no guarantee that which thread is allocated for what time to run by the processor and in that case the result is unpredictable and will generate different output for each run."

However when i tested the idea that the results are unpredictable with the other way of making threads(implements Runnable), the results were always interweaved and the same. Can anyone explain this consistency compared to extending Thread? Code for implements Runnable

class Runner implements Runnable{
    @Override
    public void run() {
        // TODO Auto-generated method stub
        for(int i =0; i< 10; i++){
            System.out.println("Hello " + i);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
        }
    }

}
public class App {
    public static void main(String[] args){

        Thread t1 = new Thread(new Runner());
        Thread t2 = new Thread(new Runner());
        t1.start();
        t2.start();
    }
}

And the output (consistent) : https://i.sstatic.net/cGJeM.jpg


Solution

  • As multiple commenters have already pointed out, it's quite possible that interweaving is indeed already happening with your code. I've tested it on my workstation and order of the thread execution is unpredictable.

    screenshot

    Based on your username, I would urge you to participate to Coursera course "Programming Mobile Services for Android Handheld Systems".

    It includes multiple patterns and examples about multithreading. Such as this incorrectly implemented ping pong application, which produces the effects that you are after: PingPongWrong.java