1

I am new to MultiThreading. I am trying below mentioned example:

class Multi implements Runnable {
public void run() {

    for (int i = 0; i < 5; i++) {
        try {
            Thread.sleep(500);
            System.out.println(Thread.currentThread().getName()
                    + " is running..."+i);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

public static void main(String args[]) {
    Multi m1 = new Multi();
    Multi m2 = new Multi();
    Thread t1 = new Thread(m1, "t1");
    Thread t2 = new Thread(m2, "t2");
    t1.start();
    t2.start();
}
}

What difference will it create if I create both threads from same Multi Class object, although output is same?

    Multi m1 = new Multi();
    Thread t1 = new Thread(m1, "t1");
    Thread t2 = new Thread(m1, "t2");
Dev
  • 13,492
  • 19
  • 81
  • 174
  • You should try it and see. Because the value of `i` is local to the method `run`, each time it is run, it will always start from `0` (for each thread), regardless of how many threads might be trying to execute it – MadProgrammer Aug 03 '15 at 05:46
  • Runnable represent a task which is executed by Thread. So if you pass same runnable/task to different threads then if there are some instance members available in runnable then those can be accessed between threads. – Sandeep Bhardwaj Aug 03 '15 at 05:57

0 Answers0