Want to know difference between below two codes
My first code is
package com.app.myclasses;
class RunnableTest implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
}
}
public class ThreadTesting {
public static void main(String[] args) {
RunnableTest r1 = new RunnableTest();
Thread t1 = new Thread(r1, "first");
t1.start();
Thread t2 = new Thread(r1, "second");
t2.start();
}
}
In above code i have created two thread by using only one runnable instance
Now have a look at below code
package com.app.myclasses;
class RunnableTest implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
}
}
public class ThreadTesting {
public static void main(String[] args) {
RunnableTest r1 = new RunnableTest();
RunnableTest r2 = new RunnableTest();
Thread t1 = new Thread(r1, "first");
t1.start();
Thread t2 = new Thread(r2, "second");
t2.start();
}
}
In second code i have created two runnable instances r1 and r2 and threads are created accordingly
So what is difference in above two codes? Is there any memory use issue or performance issue or one of them is not actually multithreading?
Method local variables are implicitly thread-safe. So, it doesn't matter in your case since i is not-shared.
Consider a case like this :
class RunnableTest implements Runnable {
int i = 0;
@Override
public void run() {
// TODO Auto-generated method stub
for (i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + " : " + i);
}
}
}
Now,
class ThreadTesting {
public static void main(String[] args) {
RunnableTest r1 = new RunnableTest();
Thread t1 = new Thread(r1, "first");
t1.start();
Thread t2 = new Thread(r1, "second");
t2.start();
}
}
The above code will not give you correct output (0-4 twice). The output will be something like :
first : 0
second : 0
first : 1
second : 2
first : 3
second : 4
We have instance level fields ( that are shared) here. So, the output is not what you expect.
In the other case, the instance level fields are not shared amongst threads. Since you have 2 different runnables.
If you want to synchronize inside the runnable instance and if you use this, then working on only one instance will be correct instead of 2 seperate runnable instances.
Note : Locking on the runnable instance is considered as bad design.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With