This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
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


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.
 
GeeCON Prague 2014
 
subject: Thread Question