LinuxQuestions.org
Download your favorite Linux distribution at LQ ISO.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 05-14-2007, 12:53 PM   #1
plk
Member
 
Registered: May 2007
Location: Krakow, Poland
Distribution: Dell Inspiron 6400 - Intel Core 2 Duo - Ubuntu 8.04
Posts: 57

Rep: Reputation: 15
Java Threads


Hiya, just wondering if anyone could tell me how to create a thread pool (by implementing Runnable) of say 20 threads executing task T ?
Thanks in Advance.

I would be looking for actual code not explanation :-)

plk
 
Old 05-14-2007, 03:36 PM   #2
Mega Man X
LQ Guru
 
Registered: Apr 2003
Location: ~
Distribution: Ubuntu, FreeBSD, Solaris, DSL
Posts: 5,339

Rep: Reputation: 65
Homework? Either way, this is not exactly what you are looking for, but it is easy to modify. You can pass as many threads as you wish as parameters in the ThreadPoolTest class.

Code:
import java.util.LinkedList;

/**
    A thread pool is a group of a limited number of threads that
    are used to execute tasks.
*/
public class ThreadPool extends ThreadGroup {

    private boolean isAlive;
    private LinkedList taskQueue;
    private int threadID;
    private static int threadPoolID;

    /**
        Creates a new ThreadPool.
        @param numThreads The number of threads in the pool.
    */
    public ThreadPool(int numThreads) {
        super("ThreadPool-" + (threadPoolID++));
        setDaemon(true);

        isAlive = true;

        taskQueue = new LinkedList();
        for (int i=0; i<numThreads; i++) {
            new PooledThread().start();
        }
    }


    /**
        Requests a new task to run. This method returns
        immediately, and the task executes on the next available
        idle thread in this ThreadPool.
        <p>Tasks start execution in the order they are received.
        @param task The task to run. If null, no action is taken.
        @throws IllegalStateException if this ThreadPool is
        already closed.
    */
    public synchronized void runTask(Runnable task) {
        if (!isAlive) {
            throw new IllegalStateException();
        }
        if (task != null) {
            taskQueue.add(task);
            notify();
        }

    }


    protected synchronized Runnable getTask()
        throws InterruptedException
    {
        while (taskQueue.size() == 0) {
            if (!isAlive) {
                return null;
            }
            wait();
        }
        return (Runnable)taskQueue.removeFirst();
    }


    /**
        Closes this ThreadPool and returns immediately. All
        threads are stopped, and any waiting tasks are not
        executed. Once a ThreadPool is closed, no more tasks can
        be run on this ThreadPool.
    */
    public synchronized void close() {
        if (isAlive) {
            isAlive = false;
            taskQueue.clear();
            interrupt();
        }
    }


    /**
        Closes this ThreadPool and waits for all running threads
        to finish. Any waiting tasks are executed.
    */
    public void join() {
        // notify all waiting threads that this ThreadPool is no
        // longer alive
        synchronized (this) {
            isAlive = false;
            notifyAll();
        }

        // wait for all threads to finish
        Thread[] threads = new Thread[activeCount()];
        int count = enumerate(threads);
        for (int i=0; i<count; i++) {
            try {
                threads[i].join();
            }
            catch (InterruptedException ex) { }
        }
    }


    /**
        A PooledThread is a Thread in a ThreadPool group, designed
        to run tasks (Runnables).
    */
    private class PooledThread extends Thread {


        public PooledThread() {
            super(ThreadPool.this,
                "PooledThread-" + (threadID++));
        }


        public void run() {
            while (!isInterrupted()) {

                // get a task to run
                Runnable task = null;
                try {
                    task = getTask();
                }
                catch (InterruptedException ex) { }

                // if getTask() returned null or was interrupted,
                // close this thread by returning.
                if (task == null) {
                    return;
                }

                // run the task, and eat any exceptions it throws
                try {
                    task.run();
                }
                catch (Throwable t) {
                    uncaughtException(this, t);
                }
            }
        }
    }
}
Code:
public class ThreadPoolTest {

    public static void main(String[] args) {
        if (args.length != 2) {
            System.out.println("Tests the ThreadPool task.");
            System.out.println(
                "Usage: java ThreadPoolTest numTasks numThreads");
            System.out.println(
                "  numTasks - integer: number of task to run.");
            System.out.println(
                "  numThreads - integer: number of threads " +
                "in the thread pool.");
            return;
        }
        int numTasks = Integer.parseInt(args[0]);
        int numThreads = Integer.parseInt(args[1]);

        // create the thread pool
        ThreadPool threadPool = new ThreadPool(numThreads);

        // run example tasks
        for (int i=0; i<numTasks; i++) {
            threadPool.runTask(createTask(i));
        }

        // close the pool and wait for all tasks to finish.
        threadPool.join();
    }


    /**
        Creates a simple Runnable that prints an ID, waits 500
        milliseconds, then prints the ID again.
    */
    private static Runnable createTask(final int taskID) {
        return new Runnable() {
            public void run() {
                System.out.println("Task " + taskID + ": start");

                // simulate a long-running task
                try {
                    Thread.sleep(500);
                }
                catch (InterruptedException ex) { }

                System.out.println("Task " + taskID + ": end");
            }
        };
    }

}
All credits to David Brackeen, author of one of the coolest Java books around: Developing Games in Java, which is the base of many of my games.

Regards!

Last edited by Mega Man X; 05-14-2007 at 03:39 PM.
 
Old 05-14-2007, 04:03 PM   #3
plk
Member
 
Registered: May 2007
Location: Krakow, Poland
Distribution: Dell Inspiron 6400 - Intel Core 2 Duo - Ubuntu 8.04
Posts: 57

Original Poster
Rep: Reputation: 15
Kinda Homework :-)
Exam on Wednesday and I kinda missed the lectures on thread pools. I can see that here threads are creating by extending the Thread class, I've been told that its a bad practice, and that its better to implement the Runnable interface, I guess that it does not make any big difference for my level application codes but we've been told to implement Runnable as a good coding practice.
Anyway thanks for this code. :-)

Back to cramming .....

plk
 
Old 05-14-2007, 04:15 PM   #4
Mega Man X
LQ Guru
 
Registered: Apr 2003
Location: ~
Distribution: Ubuntu, FreeBSD, Solaris, DSL
Posts: 5,339

Rep: Reputation: 65
You're welcome.

Now, extending a class or implementing an interface is often one of the funniest discussions one can have with Java and it can easily lead to a flamebait, so I'm not touching that with a sixty foot pole . But you may want to read an article about that:

http://www.javaworld.com/javaworld/j...-abstract.html

Regards!
 
Old 05-14-2007, 04:54 PM   #5
Alien_Hominid
Senior Member
 
Registered: Oct 2005
Location: Lithuania
Distribution: Hybrid
Posts: 2,247

Rep: Reputation: 53
You can extend only one class so that's why implementing is better.
 
Old 05-14-2007, 05:43 PM   #6
plk
Member
 
Registered: May 2007
Location: Krakow, Poland
Distribution: Dell Inspiron 6400 - Intel Core 2 Duo - Ubuntu 8.04
Posts: 57

Original Poster
Rep: Reputation: 15
true :-) thats what we've been told :-)
Anyway, that article is pretty good :-)

plk
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
more java threads: trscookie Programming 2 06-19-2006 05:11 AM
Java threads listed using kill -3 does not contain all threads found using ps -auxww coneheed Programming 2 11-14-2005 08:57 AM
java threads poeta_boy Programming 1 06-14-2005 04:34 PM
Java Threads - are they really redhatrosh Programming 1 04-05-2005 02:04 AM
Java Threads vs Native Threads rjmendez Programming 0 08-16-2004 05:58 AM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 11:19 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration