views:

163

answers:

5

I am at the end of my first year doing computer science and want to mess around with something basic. I want to use threads so I can learn.

What are some good examples to learn from?

+8  A: 

You should try the java tutorials from Sun on concurrency.

yx
And http://www.javaconcurrencyinpractice.com/ (The site, and preferably the book).
Yuval F
yes, that's a great book, definitely worth getting if he wants to pursue this further than very simple examples.
yx
A: 

Image processing and retrieving web data typically block the user interface, making them good candidates for a multithreaded design.

Marc Charbonneau
+1  A: 

ServerSocket examples are pretty simple to test and use threading pretty succinctly.

Tom Hubbard
+1  A: 

I recommend the book Concurrent Programming in Java: Design Principles and Patterns by Doug Lea. Doug Lea was one of my professors at SUNY Oswego - great professor, brilliant man. The book is excellent and gives you a ton of great information on writing good multithreaded code in Java.

Oh yeah, and Doug Lea wrote most of java.util.concurrent. So he's a pretty good authority on the subject ;-)

unforgiven3
A: 

I started by writing batch processing tools, deciding that I don't like to wait, and looking for ways to process the files in parallel. Excuse the pseudo-code; my java is really rusty.

Consider the case where you do something that takes a while several times:

foreach(var item in list)
{
    doSomethingSlow(item);
}

In this case it might be beneficial to add some dispatch code to build a thread out of the method call. I think the normal java way to do that would be to shell off an anonymous thread as follows. If you need to be able to point to the thread for more control, cancellation, etc. you will have to implement and instantiate a class that inherits from Thread.

new Thread({
    public void run(){
        doSomethingSlow(item);
    }
}).start();

Note: I haven't checked that this is the correct syntax, use at your own peril.

That approach should save you some time and open the door to thinking crudely in parallel. You can also look at loop unwinding and play with the many different parallel class libraries now available.

I generally dislike toy examples for code, and prefer to learn by creating something useful, so after playing with the ideas in some tutorials for a while, I recommend you start putting a little bit of sensible concurrent code in all your projects every time it makes sense to do so. I would not recommend you try to make every line of code parallel, as it gets very difficult to debug and introduces far too much overhead instantiating threads everywhere.

IanGilham