If your text can change and will only
be accessed from a single thread, use
a StringBuilder because StringBuilder
is unsynchronized.If your text can changes, and will be
accessed from multiple threads, use a
StringBuffer because StringBuffer is
synchronous.
What does it mean by multiple threads? Can anyone explain me over this? I mean is it something two methods or two programs trying to access another method at same time.
Threads are paths of execution that can be executed concurrently. You can have multiple threads in your Java program, which can call the same method of the same object at the same time. If the method e.g. prints something on screen, you might see the messages coming from different threads jumbled up – unless you explicitly ensure that only one message can be printed out at a time, and all other requests to print shall wait until the actual message is fully printed.
Or, if you have a field in that object, all threads see it. And if one of them modifies the field… that’s when the interesting part begins 🙂 Other threads may only see the updated value at a later time, or not at all, unless you specifically ensure that it is safe to use by multiple threads. This can result in subtle, hard to reproduce bugs. This is why writing concurrent programs correctly is a difficult task.
On machines with a single processor core, only a single thread can run at any time, thus different threads are executed one after another, but the OS switches between them frequently (many times per second), thus giving the user the illusion of seeing multiple threads running in parallel. OTOH multicore machines can really run several threads at the same time – as many as processor cores they have.
Every Java program has at least one thread. You may manually create additional threads within your program and pass them tasks to execute.
A detailed explanation of threads and processes – and further, concurrency in Java – can be found in the Java Tutorials.