Java Thread Pool Easy Tutorial

Runnable Class [the class that will be executed by the thread pool]

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package MainTaskClass;

import java.security.SecureRandom;
import java.util.Random;

/**
*
* @author Administrator
*/
public class RunnableClass implements Runnable {

    private int sleeptime;
    private String threadName;
    private SecureRandom random = new SecureRandom();

    public RunnableClass(String threadName){
        this.threadName = threadName;
    }

    public void run() {
        try {           
            sleeptime = random.nextInt(5000);
            System.out.printf("%s going to sleep for %d milliseconds \n", threadName, sleeptime);
            Thread.sleep(sleeptime);

        } catch (InterruptedException exp) {
            exp.printStackTrace();
        }
            System.out.printf("%s Done Sleeping \n`", threadName);
    }
}

 

 

Thread Pool… that will run the CustomRunnable class

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package MainTaskClass;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
*
* @author Administrator
*/
public class CustomRunnable {
    public static void main(String are[]){
        RunnableClass run1 = new RunnableClass("Phelaa");
        RunnableClass run2 = new RunnableClass("Dosraa");
        RunnableClass run3 = new RunnableClass("Teesraa");
        System.out.println("Thread Dohraaa dyrea :) ");
        //going to manage threads by using Executor service
        ExecutorService service = Executors.newFixedThreadPool(17);
        service.execute(run1);
        service.execute(run2);
        service.execute(run3);
        service.execute(run1);
        service.execute(run2);
        service.execute(run3);
        service.execute(run1);
        service.execute(run2);
        service.execute(run3);
        service.execute(run1);
        service.execute(run2);
        service.execute(run3);
        service.execute(run1);
        service.execute(run2);
        service.execute(run3);
        service.execute(run1);
        service.execute(run2);

        service.shutdown();
    }

}

2 comments:

  1. thanks, it was really simple & useful !

    ReplyDelete
  2. cοnstantly i usеd to геad smaller artіcles or reνieωs whiсh also cleаr their mоtiѵe, and that is also happening
    wіth thiѕ paragraph which I am reаding at this time.


    Τakе a look at my weblog; Recommended Web-site

    ReplyDelete