Skip to the content.

Concurrency

Concurrency

-

Thread Object

-

Thread scheduler

-

Thread States

-

Thread States
New

-

Thread States
Runnable

-

Thread States
Blocked, Waiting, Timed Waiting

-

Thread States
Terminated

-

Runnable Interface

public void demo() {
  Runnable runnable = ()->System.out.println("Hello world!");
  Thread thread = new Thread(runnable);
  thread.start(); // begins an independent thread of execution
}

-

Thread Interruption

-

Delaying Execution

public void demo() {
  try {
    Thread.sleep(5000);
  } catch(InterruptedException e) {
    e.printStackTrace();
  }
}

-

Encapsulating InterruptedException

public class ThreadUtils {
  public static void sleep(Integer milliseconds) {
    try {
      Thread.sleep(milliseconds);
    } catch(InterruptedException e) {
      e.printStackTrace();
    }
  }
}

-

Thread Interruption
Example 1

public void demo() {
    Runnable runnable = this::execute;
    Thread t = new Thread(runnable);
    t.start();
    ThreadUtils.sleep(5000);

    System.out.println("I'M GONNA STOP THE THREAD NOW!");
    t.interrupt();
}

public void execute() {
    while (!Thread.currentThread().isInterrupted()) {
        System.out.println("I AM RUNNING!");
    }
}

Output

I AM RUNNING!
I AM RUNNING!
I'M GONNA STOP THE THREAD NOW!
I AM RUNNING!
I AM RUNNING!

-

Asynchronous Threading