Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Methods Running in threads

I understand the concept behind threading and have written threads in other languages, but I am having trouble understanding how to adapt them to my needs in java.

Basicly at present I have a vector of objects, which are read in from a file sequentially. The file then has a list of events, which need to happen concurrently so waiting for one event to finish which takes 20-30 seconds is not an option.

There is only a couple of methods in the object which deal with these events. However from looking at tutorials, objects must extend/implement threads/runnable however if the object is in a thread making a method call to that object seems to happen sequentially anyway.

An y extra information would be appreciated as I am clearly missing something I am just not quite sure what!

So to summarise how can I execute a single method using a thread?

like image 773
john Avatar asked Feb 18 '10 21:02

john


1 Answers

To start a thread you call start() on an instance of Thread or a subclass thereof. The start() method returns immediately. At the same time, the other thread (the one incarnated by the Thread instance) takes off, and proceeds with executing the run() method of the Thread instance.

Managing threads is not as easy as it seems. For a smoother API, try using an Executor (see the classes in java.util.concurrent).

like image 185
Thomas Pornin Avatar answered Sep 29 '22 01:09

Thomas Pornin