You are getting closer. However, if you want to do it the right way, I would recommend that you get some background information.
A good source is
Java Thread Programming by Paul Hyde.
And if you
really want to understand what thread programming is all about, try
Concurrent Programming in Java by Doug Lea.
- we create a background thread with minimal priority and run it... It's not recommended to manipulate the priorities. One of the many reasons is that the Java range of priorities (from min to max) doesn't map well into the OS thread priorities.
- it puts a wait() on messages monitor... so the writeThread gets "suspended" (1.CORRECT?) More precisely, the thread is put in the "wait" state.
- first we reach the monitor ( synchronized(messages) ), and we will wait until the background thread is finished logging. Good.
2.Is this efficient btw? won't that create a bottleneck which will make the whole threading useless? Or will it work since writeThread has lower priority? ) No matter how you turn it around, you cannot both write and read from the same resource. But in your case, I would not expect a bottleneck because your "((Logger)iterator.next()).log( level, data )" operation is presumably a matter of milliseconds. But even if it was singificantly longer, it would still be beneficial, because you could still coninue running your app without waitng until the log operation completes.
Incidentally, I don't see where you dequeue the messages, -- is there a reason that you write the same messages over and over again?
- we'll notify the messages monitor that it is ready to log ( 3. CORRECT? ) Yep.
But even if I declare that variable as violatile (can you explain what its for?) The concept of "volatile" deserves its own thread, but I am sure you will get a few hits if you search for in in this forum.
how would I terminate it AUTOMATICALLY, whenever JVM terminates or it gets GC? Well,
something happens before your program terminates, right? You probably click some "Exit" menu item at which point you must be doing some clean up. As part of that clean-up, call the method on your object that sets the boolean and terminates the thread.
I was also thinking...
that instead of having a background logging thread running forever and logging data that is in the queue, I could have a NEW thread created every time some data has been enqueued, and have that thread as a background thread... So for every piece of data I'd have its own background thread...
Certainly possible, that's a matter of your requirements and the design.