Jump to content

Threading

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
1 reply to this topic

#1
Guest_Grouchotron_*

Guest_Grouchotron_*
  • Guests
Hey, I've seen two different ways to implement threading in java, and was wondering what the advantages were to each method, and if there were any better ways.

Or if its easier just link me to some good resources on the topic.

The first method being creating a Thread object and passing in an object that implements runnable

The second being create an ExecutorService threadpool and an arraylist of callable<String>, each callable being a method containing a method call to what i want threaded, then calling pool.invokeAll(tasks). Tasks being your arraylist of callables.

#2
Stu_328

Stu_328

    Learning Programmer

  • Members
  • PipPipPip
  • 92 posts
Basically always use the implements Runnable method.

The thing with extending Thread has 2 problems:

1. It's not very good OO. Say you have a car object that extends Thread. Then you have a car that is a Thread. From an OO perspective that just doesn't make sense. It would make much more sense to be a Car that was Runnable.

2. You can only extend 1 class. If you want to create a Honda object that already extended Thread and there was a superclass that was called Car it would make sense for the Honda to extend Car, right? But Honda can't because it already extends Thread.

Polymorphism (implements) is for implementing the same thing in different ways. Inheritance (extends) is for implementing different objects to do the same thing in the same way.

HTH

EDIT: Sorry I completely mis read your question.

With regard to the ExecutorService, you would use this if your code could arbitrarily create new Threads and you wanted to cap the amount and control the number of Threads in existence at any one time.

You normally only really need to start a new Thread with Runnable, otherwise it's just over engineering.

Also, try reading this:

Java theory and practice: Thread pools and work queues

HTH :)