aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Thread Question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Thread Question" Watch "Thread Question" New topic
Author

Thread Question

RAGU KANNAN
Ranch Hand

Joined: Dec 16, 2005
Posts: 103
Hello Folk's

I would like to know what is the differnet between Line 4 and Line1,2,3.
The line4 not using to thread to call the runnable. Pls exaplaint to me.

Thanks, Raghu.K


class Reader extends Thread {
Calculator c;
public Reader(Calculator calc) {
c = calc;
}

public void run() {
synchronized (c) {
try {
System.out.println("Waiting for calculation...");
c.wait();
} catch (InterruptedException e) {
}
}
System.out.println("Total is: " + c.total);
}

public static void main(String[] args) {
Calculator calculator = new Calculator();
new Reader(calculator).start(); //Line 1
new Reader(calculator).start(); //Line 2
new Reader(calculator).start();//Line 3
calculator.start();//Line 4
}
}

class Calculator extends Thread {
int total;

public void run() {
synchronized (this) {
for (int i = 0; i < 100; i++) {
total += i;
}
notifyAll();
}
}
}
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
Calculator is a subclass of Thread so it inherits the start() method.
Gowher Naik
Ranch Hand

Joined: Feb 07, 2005
Posts: 643
The difference between line4 and Line 1, Line 2 and Line 3 is that
Line 1, Line 2 and Line 3 creates three separate threads of type Reader.
All theses threads wait for Calculator thread to notify.
Line 4 starts separate thread of type Calculator which notifies all Reader threads.
Only problem with this program is that if Calculator thread(line4) starts first (which is very unlikely)Then all Reader threads will wait for ever.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Thread Question
 
Similar Threads
blocking and waiting
Thread question in an example of Kathy and Bert Book
Code using notifyAll() runs indefinitely
Question regarding notify() and wait()
blocking and waiting