I have the following code but it’s output is not what I expected:
public class ThreadManager {
public static void main(String[] args) {
Resource sharedResource = new Resource();
new Thread(new MyThread(sharedResource)).start();
new Thread(new MyThread(sharedResource)).start();
}
}
class MyThread implements Runnable{
Resource rs = null;
public MyThread(Resource param) {
this.rs = param;
}
@Override
public void run() {
this.rs.add(Thread.currentThread().getName());
System.out.println(this.rs.str);
}
}
class Resource{
StringBuilder str = new StringBuilder();
public void add(String text){
str.append(text);
}
}
output is :
Thread-0Thread-1
Thread-0Thread-1
but how…
here if thread 0 is executed first then output should be
Thread-0
Thread-0Thread-1
but here issue is the thread-1 in the first line of output.
What makes you think that just because you start thread 0 first, it will get to the
addmethod call first? And even if one thread does get to theaddcall first, that doesn’t mean it will reach the next statement (System.out.println) before the other thread has had a chance to calladd. It looks like that’s the situation here:addaddSystem.out.println(this.rs.str)System.out.println(this.rs.str)(That’s a little bit hand-wavy, in that those aren’t atomic operations, but it’s a possible flow.)
Imagine your two threads are athletes on a running track – the order in which you start them isn’t necessarily the same as the order in which they cross the finish line.
Also note that
StringBuilderisn’t designed to be safe for access from multiple threads.