0

I have two Thread class. buyThread and sellThread .Inside the tester program, I need to declare and create 2 threads object belong to buyThread and sellThread, and do a run and join threads.

Thread bt[] = new Thread[2]; // declare and create 2 threads object
    Thread st[] = new Thread[2]; // declare and create 2 threads object

    for (int i = 0; i < 2; i++) {
        bt[i] = new BuyThread(rand1, rand2, stock);
        bt[i].start();
    }

    for (int i = 0; i < 2; i++) {
        st[i] = new SellThread(rand1, rand2, stock);
        st[i].start();
    }

    for (int i = 0; i < 2; i++) // Can I do it this way for each Thread ?
    {
        try {
            bt[i].join();
        } catch (InterruptedException e) {
        }
    }
    for (int i = 0; i < 2; i++) {
        try {
            st[i].join();
        } catch (InterruptedException e) {
        }
    }
Patrick
  • 33,984
  • 10
  • 106
  • 126
  • 2
    and what is the problem? you declare 4 threads anyway (but you don't start any of them.) -- ook, you edited the question but still what is the problem? .join method will let the main thread to wait until all threads are finished – Marco Acierno Feb 12 '14 at 17:20
  • May I check is this the correct way to write a join() ? – newbie_Roy Feb 12 '14 at 17:23
  • Can I just write for (int i=0; i < 2; i ++) { try { st[i].join(); bt[i] } catch (InterruptedException e) {} } – newbie_Roy Feb 12 '14 at 17:25
  • Well, you already know what will be the threads to join (0, 1) so you can just do st[0].join(); st[1].join(); and avoid for – Marco Acierno Feb 12 '14 at 17:25
  • 1
    So what is the problem exactly? As a side note, I recommend to [_not_ extend Thread](http://stackoverflow.com/a/541506/836214) and instead use an [ExecutorService](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html) to manage your tasks... – Krease Feb 12 '14 at 17:25
  • You can write for (int i = 0; i < 2; ++i) { st[i].join(); bt[i].join(); } too. No indexs problems (if you keep 2 indexs) – Marco Acierno Feb 12 '14 at 17:25

1 Answers1

0

Your join is fine.

Note that you're waiting for both BuyThread instances to complete first, and then waiting for both SellThread instances to complete (in that order).

The benefit of shoving everything into an array is that you only need to add new instances of each Buy/Sell thread class into the array, and your app will wait for all of them to finish.

Isn't that what you wanted?

Edit: As mentioned in comments, you should implement runnable instead of extending the Thread class. That's cleaner. See this question for details.

Community
  • 1
  • 1
ashes999
  • 9,925
  • 16
  • 73
  • 124