Thursday, 17 March 2016

How many ways to create threads and thread pools ?


2 ways to create thread :
  1. Define a class that extends Thread class
  2. Define a new class that implements Runnable interface, and pass an object of that class to a Thread's constructor. It allows to extend one class.





Example (Thread)
class MyThread extends Thread {
    public void run() {
        System.out.println("I'm running!");
    }
}

public class TestThread {
    public static void main(String[] args) {
        MyThread my1 = new MyThread();
        MyThread my2 = new MyThread();
        my1.start();
        my2.start();
    }
}


Example (Runnable)
class
MyRunnable implements Runnable {
    public void run() {
        System.out.println("I'm running!");
    }
}

public class TestRunnable {
    public static void main(String[] args) {
        MyRunnable my1 = new
MyRunnable();
       
MyRunnable my2 = new MyRunnable();
        new Thread(my1).start();
        new Thread(my2).start();
    }
}



+2 way to create Thread pool :
  1. Define a class that extends ThreadPoolExecutor class.

  2. Define a class that extends ScheduledThreadPoolExecutor class, which provides scheduling.

Example (ThreadPoolExecutor)

int MAX_SIZE = 10;
ExecutorService exec = Executors.newFixedThreadPool(MAX_SIZE);
for (int i = 0; i < MAX_SIZE; i++) {
  exec.execute(new Runnable() {
      public void run() {

          .....
      }
  });

}



* There are 2 factories newFixedThreadPool and newCachedThreadPool to create instances of ThreadPoolExecutor.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.