Thursday, April 14, 2011

How to implement multiple threads in Java

How do I implement multiple threads in Java?

From stackoverflow
  • Start here: Java Sun Tutorial, Lesson: Concurrency

    And perhaps focus on this part: High Level Concurrency Objects

  • You could do it this way:

    Write a class that implements Runnable interface and put the thread code in the run() method.

    public class MyThreadedClass implements Runnable {
       public void run()
       {
          // put your thread code here
       }
    }
    

    And then, create the thread anywhere you want like this.

    (new Thread(new MyThreadedClass())).start();
    

    That's a very simple cookbook.

    Don't forget to read about synchronization and concurrency as other post is suggesting. It's very important when dealing with threads.

    Steve Kuo : You don't need parentheses around new Thread(...)
  • I would recommend reading Concurrent Programming in Java by Doug Lea.

    Adam Jaskiewicz : Java Concurrency in Practice is also good.
  • This book might be useful to you.

    http://www.flazx.com/ebook3925.php

0 comments:

Post a Comment