943,746 Members | Top Members by Rank

Ad:
  • Java Discussion Thread
  • Marked Solved
  • Views: 1462
  • Java RSS
Oct 21st, 2008
0

How to know when a thread ends.

Expand Post »
Hi all,

I have a multi-threaded program. This program, lets say spawns 10 threads. I would like to update a variable when each thread finishes its job.

The reason why I am asking this, is because I would like to show something like progress bar (not really a progress bar, but display a precentage of job completion, while the program is running).

I have this thaugh, and someone please correct me if I am wrong.

I have the following classes

- MainProgram.java
- MainProgramThread.java
- MainProgramProgressThread.java

If MainProgram creates 10 instance of MainProgramThread class, I would like to decrement a counter (which has the maximum number of threads running)

On the other hand, MainProgramProgressThread class will only display the progress percentage (this will be calculated) so long as the number of counter is greater than zero when this value reaches 0, then I would like the ProgressThread to stop.

So, my question is how can I know when a thread ends?

Or if there's another way of doing what I would like to do, I am open to ideas.

Thanks in advance...
Similar Threads
Reputation Points: 7
Solved Threads: 6
Junior Poster
new_2_java is offline Offline
127 posts
since Apr 2007
Oct 22nd, 2008
0

Re: How to know when a thread ends.

Inside the run method of the Thread class have a boolean method take value true when it finishes. That variable will be declared as an attribute of the class.

When you call the thread have a while loop checking that variable when it becomes true you will exit the loop
Sponsor
Featured Poster
Reputation Points: 1014
Solved Threads: 446
Nearly a Senior Poster
javaAddict is offline Offline
3,258 posts
since Dec 2007
Oct 22nd, 2008
0

Re: How to know when a thread ends.

Thanks for the info.

So, lets consider the following code. Please correct me if I am wrong.

java Syntax (Toggle Plain Text)
  1. public class MainClass {
  2. int final MAX = 10;
  3. int counter = MAX;
  4. public static void main (String[] arg) {
  5. for (int i=0; i < MAX; i++) {
  6. ThreadClass tc = new ThreadClass();
  7. tc.start();
  8. }
  9. }
  10.  
  11. public static synchronized void updateCounter() {
  12. counter--;
  13. }
  14. public int getCounter () {
  15. return counter;
  16. }
  17. }
  18.  
  19. //----------------------------
  20. public class ThreadClass extends Thread {
  21. public void run () {
  22. while (some condition is true) {
  23. doSomeOperationHere();
  24. }
  25. MainClass.updateCounter();
  26. }
  27. }
  28.  
  29. //-------------------------------
  30. public class ProgressThread extends Thread {
  31. public void run () {
  32. while (MainClass.getCounter() > 0) {
  33. // calculate and display progress bar
  34. }
  35. }
  36. }

Will this work?

Thanks.
Reputation Points: 7
Solved Threads: 6
Junior Poster
new_2_java is offline Offline
127 posts
since Apr 2007
Oct 22nd, 2008
0

Re: How to know when a thread ends.

Here's one way you could monitor progress on the tasks. It involves timed polling of the progress of each task.
java Syntax (Toggle Plain Text)
  1. import java.util.ArrayList;
  2. import java.util.List;
  3. import java.util.concurrent.Callable;
  4. import java.util.concurrent.ExecutorService;
  5. import java.util.concurrent.Executors;
  6. import javax.swing.ProgressMonitor;
  7.  
  8. public class ProgressDemo {
  9.  
  10. public static void main(String[] args) {
  11. WorkQueue work = new WorkQueue();
  12. work.begin();
  13. }
  14.  
  15. static class WorkQueue {
  16.  
  17. final int NUM_THREADS = 5;
  18. ExecutorService execService =
  19. Executors.newFixedThreadPool(NUM_THREADS);
  20.  
  21. int totalThingsToDo = 0;
  22. int percentComplete = 0;
  23.  
  24. public void begin() {
  25. totalThingsToDo = 100;
  26. List<LongTask> tasks = new ArrayList<LongTask>();
  27.  
  28. // create and submit tasks to thread pool
  29. for (int i = 0; i < NUM_THREADS; i++) {
  30. LongTask task =
  31. new LongTask(totalThingsToDo/NUM_THREADS, i);
  32. tasks.add(task);
  33. execService.submit(task);
  34. }
  35.  
  36. ProgressMonitor monitor = new ProgressMonitor(null,
  37. "Doing stuff...", "", 0, 100);
  38.  
  39. // monitor progress until done
  40. while (percentComplete < 100) {
  41. int partialProgress = 0;
  42. for (LongTask task : tasks) {
  43. partialProgress += task.getProgress();
  44. }
  45. percentComplete =
  46. (int)(partialProgress / (float)tasks.size());
  47.  
  48. try {
  49. // wait one second between progress updates
  50. Thread.sleep(1000);
  51. } catch (InterruptedException ie) {
  52. Thread.currentThread().interrupt();
  53. }
  54.  
  55. monitor.setNote(percentComplete+" %");
  56. monitor.setProgress(percentComplete);
  57. }
  58. // shutdown the thread pool
  59. execService.shutdown();
  60. }
  61. }
  62.  
  63. /** Mock task that does an arbitrarty number
  64.   * of "things" in a random amount of time.
  65.   */
  66. static class LongTask implements Callable<Boolean> {
  67.  
  68. int thingsToDo = 0;
  69. int thingsDone = 0;
  70. int taskId=0;
  71.  
  72. public LongTask(int thingsToDo, int taskId) {
  73. this.thingsToDo = thingsToDo;
  74. this.taskId = taskId;
  75. }
  76.  
  77. public Boolean call() throws Exception {
  78. boolean completed = false;
  79. while (thingsDone < thingsToDo) {
  80. // random pause to simulate "working"
  81. Thread.sleep((int)(Math.random() * 3000));
  82. thingsDone++;
  83. }
  84. System.out.println(taskId + " done");
  85. return Boolean.valueOf(completed);
  86. }
  87.  
  88. public int getProgress() {
  89. return (int)(thingsDone / (float)thingsToDo * 100f);
  90. }
  91. }
  92. }
Alternately, you could provide a reference to the WorkQueue class to the tasks and a call-back method that each task could use to publish it's progress (basically making the WorkQueue a listener for progress updates generated by the tasks). An example of that implementation can be seen here in the Swing progress bar tutorial: http://java.sun.com/docs/books/tutor.../progress.html
Moderator
Featured Poster
Reputation Points: 3239
Solved Threads: 838
Posting Genius
Ezzaral is offline Offline
6,761 posts
since May 2007
Oct 23rd, 2008
0

Re: How to know when a thread ends.

Thanks Ezzaral. I used a counter to determine whether each thread is finished. And it's working now.
Reputation Points: 7
Solved Threads: 6
Junior Poster
new_2_java is offline Offline
127 posts
since Apr 2007
Oct 23rd, 2008
0

Re: How to know when a thread ends.

Glad to hear it. I posted that example around the same time that you posted what you were trying, so there was a little overlap. It also went a little bit further than your stated goal of just using thread completion to increment progress, but the intent was to show a progress polling mechanism. Your own code basically uses the alternative mechanism I mentioned at the bottom of the post, with each thread calling back to a central method to report progress. Collectively those two mechanisms represent a push versus pull paradigm in the communication process.
Moderator
Featured Poster
Reputation Points: 3239
Solved Threads: 838
Posting Genius
Ezzaral is offline Offline
6,761 posts
since May 2007

This thread is solved

Either the thread starter or a moderator has marked this thread as solved. You can most likely trust the responses and answers given. There is most likely no reason for any further responses to be posted here. If you have a related question, please start a new thread in this forum instead.

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in Java Forum Timeline: search misses items
Next Thread in Java Forum Timeline: Security Manager for File.listRoots();





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC