core java – thread

Thread:

Ways to create a thread: 


1. Implements Runnable interface

class MyThread implements Runnable
{
 public void run()
 {
  System.out.println("concurrent thread started running..");
 }
}

class MyThreadDemo
{
 public static void main( String args[] )
 {
  MyThread mt = new MyThread();
  Thread t = new Thread(mt);
  t.start(); //have to call start method, otherwise, it will not create a new Thread
 }
} 
2. Extending Thread Class

class MyThread extends Thread
{
 public void run()
 {
  System.out.println("concurrent thread started running..");
 }
}

classMyThreadDemo
{
 public static void main( String args[] )
 {
  MyThread mt = new  MyThread();
  mt.start();
 }
}

2. Synchronisation:

ConcurrentHashMap vs HashTable: ConcurrentHashMap allows concurrent reading, but not writing.

3. ThreadPool

public class SimpleThreadPool {

 public static void main(String[] args) {
    ExecutorService executor = Executors.newFixedThreadPool(5);
    for (int i = 0; i < 10; i++) {
       Runnable worker = new WorkerThread("" + i);
       executor.execute(worker);
    }
    executor.shutdown();
    while (!executor.isTerminated()) {
    }
    System.out.println("Finished all threads");
 }
}
Tags:

Add a Comment