Re: [Threading to manage simulated printing jobs]
getsanjay.sharma@gmail.com wrote:
Hello to all Javascript programmers out there. :)
Wrong group. They won't be listening here.
I am really ashamed to say that even after 6 months of intermittent
Java programming I have been a complete failure at grasping the
concepts or the real thing behind 'threading'.
Join the crowd. Nearly all Java programmers have yet to grok threading.
class Consumer {
private static int gId;
Accessed by many threads, yet you don't synchronize those accesses. Not safe.
Do not use TAB characters in Usenet posts.
private PrintQueue queue;
private String id;
private Consumer() {
}
You do not need this constructor. Also, it's conventional to place all
constructor definitions together.
private Runnable job = new Runnable() {
public void run() {
// start consuming the print jobs and print them
try {
for (;;) {
//System.out.println("Inside run of producer");
Use logging, not System.out.println(). And isn't this the consumer?
Thread.sleep(10);
PrintJob job = queue.getJob();
You'd better make sure the queue is synchronized!
if (job != null)
System.out.println(id + job.print());
Use logging, not System.out.println(). And you forgot your braces.
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
public Consumer(PrintQueue queue) throws Exception {
this.queue = queue;
this.id = "Consumer" + gId;
gId++;
Synchronize!
Thread t = new Thread(job);
t.join(); /* Does this even do anything? */
Have you read the Javadocs on Thread.join?
<http://java.sun.com/javase/6/docs/api/java/lang/Thread.html#join()>
It causes the current thread to wait for the target thread to finish. Of
course, in your case it hasn't started yet.
t.start();
I am thinking it's a bad idea to fire off threads or do any significant work
in the constructor.
}
}
Buy and study /Java Concurrency in Practice/ by Brian Goetz, et al.
--
Lew