File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

doubt from scjp book on threads

 
Abhishek Mantri
Greenhorn
Posts: 25
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1. class Reader extends Thread {
2. Calculator c;
3.
4. public Reader(Calculator calc) {
5. c = calc;
6. }
7.
8. public void run() {
9. synchronized(c) {
10. try {
11. System.out.println("Waiting for calculation...");
12. c.wait();
13. } catch (InterruptedException e) {}
14. System.out.println("Total is: " + c.total);
15. }
16. }
17.
18. public static void main(String [] args) {
19. Calculator calculator = new Calculator();
20. new Reader(calculator).start();
21. new Reader(calculator).start();
22. new Reader(calculator).start();
23. calculator.start();
24. }
25. }
26.
27. class Calculator extends Thread {
28. int total;
29.
30. public void run() {
31. synchronized(this) {
32. for(int i=0;i<100;i++) {
33. total += i;
34. }
35. notifyAll();
36. }
37. }
38. }
"The program starts three threads" is this statement correct ,i think it starts 4 threads.This code is from scjp book page 724-725.
 
Wim Molenberghs
Greenhorn
Posts: 16
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The books doesn't say "the program starts three threads" but "the program starts three threads that are all waiting to receive the finished calculation"

I can be wrong but the way I read this is that there are 3 threads that are waiting + a thread to finish the calculation.

And the program has not a total of 4 threads but 5 :-)
 
Abhishek Mantri
Greenhorn
Posts: 25
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
which is the fifth thread then???
do you mean main thread?
 
Wim Molenberghs
Greenhorn
Posts: 16
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes, the main is also a thread.
don't forget this for the exam.
 
Abhishek Mantri
Greenhorn
Posts: 25
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Wim !
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic