Java Threads - ashwin-shetty/Documents-Wiki GitHub Wiki

Threads can be implemented using

  1. Extends thread
  2. Implements Runnable

A thread state

  • NEW when it is ready to run but nobody said it to run
  • RUNNABLE it is a state when thread is ready to run but other thread is getting executed
  • RUNNING it is state when thread is executing or running.
  • BLOCKED/WAITING is state while waiting for external service like database or values for execution or waiting for other thread
  • TERMINATED/DEAD is when thread has stopped execution

Thread priority. Thread can be assigned priority but this is just a request for the processed it may or may not be honored always. min priority is 1 and max is 10 MIN_PRIORITY is 1 , NORM_PRIORITY is 5 and MAX_PRIORITY is 10. It is assigned by thread.setPriority(10);

join() task1.join() when called the current thread waits for task1 thread to terminate. The next line of the code is executed only once the task1 thread is completed.

Thread Utility Method

  • Thread.sleep(100000) : Current thread will sleep (wait) for 10 seconds
  • Thread.yield() : Hint to scheduler when it is OK to give up CPU. However this is just request.

Synchronized keyword when used in method only one thread can access it. if there are multiple threads and multiple synchronized method, When one thread tries to access the Synchronized method rest of the threads can't access same or any other synchronized method. Eg: If there is 50 synchronized method then in given interval of time only one thread can use synchronized block and rest needs to wait (Even if other thread wants to use different synchronized method).

Extends thread

class Task1 extends  Thread {

    public void  run(){
        System.out.println("\n Task1 Started");
        for(int i=0; i<=99; i ++){
            System.out.print(i +" ");
        }
        System.out.println("\n Task1 Done");
    }
}
 Task1 task1 = new Task1();
 task1.start(); //  to run in thread .start() method should be used but not .run()

Implements Runnable

class Task2 implements Runnable {
    @Override
    public void run() {
        System.out.println("\n Task2 Started");
        for(int i=101; i<=199; i ++){
            System.out.print(i+ " ");
        }
        System.out.println("\n Task2 Done");
    }
}
 Task2 task2 = new Task2();
 Thread thread = new Thread(task2);
 thread.start(); //  to run in thread .start() method should be used but not .run()

Executor Service

This is used to control how many threads can run at particular time.

// Java Thread Class used in ExecutorService 
class Task extends  Thread {

    private  int number ;
    Task(int number){
    this.number = number;
    }

    public void  run() {
        System.out.println("\n Task "+ number +" : started");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("\n Task "+number+" : done");
    }
}
 // Single thread at once
ExecutorService executorService = Executors.newSingleThreadExecutor();
// Multiple thread based on the thread pool size
ExecutorService executorService = Executors.newFixedThreadPool(2);
// Executor Service Flow
 ExecutorService executorService = Executors.newFixedThreadPool(5); // Initialize the pool size 
 executorService.execute(new Task(1)); // execute thread
 executorService.execute(new Task(2));
 executorService.shutdown(); // execute needs to be closed after completing the operation or else it keeps running.

Callable

Threads that return values.The Java Callable interface represents an asynchronous task which can be executed by a separately and then return value

class CallableTask implements Callable<String> {

    private String name;

    CallableTask(String name) {
        this.name = name;
    }

    @Override
    public String call() throws Exception {
        Thread.sleep(1000);
     //   System.out.println("In thread Hello " + name);
        return "Hello " + name;
    }
}
// Callable with One Thread and One Return value
ExecutorService service = Executors.newFixedThreadPool(2);
// submit() used for Callable and execute() for Threads
Future<String> welcomeFuture = service.submit(new CallableTask("Monika")); 
String futureMessage = welcomeFuture.get();
System.out.println(futureMessage);
service.shutdown();
// Callable with Multiple Thread and Multiple Return value
ExecutorService service = Executors.newFixedThreadPool(2);
List<CallableTask> callableTasks = Arrays.asList(new CallableTask("Monika"), new CallableTask("Ashu"), 
                                                 new CallableTask("Babloo"), new CallableTask("Kruthi"));
List<Future<String>> futureList = service.invokeAll(callableTasks);
for (Future<String> future : futureList) {
 System.out.println(future.get());
}
service.shutdown();
// Callable with Multiple Thread and returns one Thread value
ExecutorService service = Executors.newFixedThreadPool(4);
List<CallableTask> callableTasks = Arrays.asList(new CallableTask("Monika"), new CallableTask("Ashu"),
                                                 new CallableTask("Babloo"), new CallableTask("Kruthi"));
String futureList = service.invokeAny(callableTasks);
System.out.println(futureList);
service.shutdown();
⚠️ **GitHub.com Fallback** ⚠️