Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Thread Question

 
RAGU KANNAN
Ranch Hand
Posts: 103
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Calculator is a subclass of Thread so it inherits the start() method.
 
Gowher Naik
Ranch Hand
Posts: 643
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic