Classes and threads are independent concepts. Classes and methods do not block; threads do.
If you have this:
MyClass mc = new MyClass();
mc.run(); // this will never return
This code runs in a single thread; the Thread.sleep(500)
runs in the thread and blocks the thread with each call. While the thread is sleeping, execution in the thread is halted. (In fact, mc.run()
will never return due to its endless loop.)
However, if more than one thread has a reference to a particular MyClass
instance, then each thread can independently make calls to methods on the object. Each thread executes independently of others (except when synchronization is involved).
MyClass mc = new MyClass();
Thread thread = new Thread(mc);
thread.start();
for (int i = 0; i < 100; ++i)
{
MyObject obj = new MyObject();
mc.addToQueue(obj);
}
This code creates a new thread (call it thread B) and starts it, which causes run()
to be executed in the new thread, on the mc
object instance. Now there are two threads -- the original one, thread A, and the new one, thread B. Both execute independently of each other. In particular, thread A can manipulate the object at (for our purposes here) the same time thread B is running run()
. If you are not careful to avoid potentially conflicting manipulations, you will experience unexpected results and difficult-to-reproduce failures. In your code, if more than one thread can call addToQueue()
on a given object without adequate synchronization, then you will eventually encounter trouble because LinkedList
is not a thread-safe class.
Concurrency and thread safety can be challenging to get correct. The book Java Concurrency in Practice by Brian Goetz, et. al. is an excellent start.