Win a copy of Escape Velocity: Better Metrics for Agile Teams this week in the Agile and Other Processes forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Tim Cooke
  • Paul Clapham
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Frank Carver
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Frits Walraven
  • fred rosenberger

Thread Question

 
Ranch Hand
Posts: 103
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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();
}
}
}
 
Ranch Hand
Posts: 2412
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Calculator is a subclass of Thread so it inherits the start() method.
 
Ranch Hand
Posts: 643
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Stop it! You're embarassing me! And you are embarrassing this tiny ad!
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic