This is the 9th day of my participation in Gwen Challenge

Preface:

A thread is a thread of execution in a program. The Java virtual machine allows applications to run multiple threads of execution concurrently.

Each thread has a priority, and high-priority threads execute before low-priority threads. Each thread may or may not be marked as a daemon. When code running in a Thread creates a new Thread object, the initial priority of the new Thread is set to the priority of the creator Thread, and the new Thread is the daemon if and only if the creator Thread is the daemon.

When a Java virtual machine starts, there is usually a single non-daemon thread (which usually calls the main method of a given class). The Java virtual machine continues executing threads until one of the following conditions occurs:

The Exit method of the Runtime class is called, and the security manager allows the exit operation to occur. All threads that are not daemons have stopped running, either by returning from a call to the run method or by throwing an exception that propagates outside the run method.

Several ways to create threads

  • Inherit the Thread class and override the run method
  • Implement the Runnable interface
  • Use Callable and Future
  • Using thread pools for example using the Executor framework

1. Create Thread by inheriting the Thread class

  • Define a subclass of Thread and override its run() method
  • Create an instance of the Thread subclass, which creates a Thread object
  • To start a thread, call the thread’s start() method
Public class ThreadTest extends Thread {@override public void run() {system.out.println (" ThreadTest extends Thread; + Thread.currentThread().getName()); } } class Main{ public static void main(String[] args) { ThreadTest threadTest = new ThreadTest(); threadTest.start(); }}Copy the code

2. Implement Runnabel

  • The implementation class that defines the Runnable interface also overwrites the run() method, which, like the run() method in Thread, is the execution body of the Thread
  • Create an instance of the Runnable implementation class and use this instance as the target of the Thread to create the Thread object, which is the actual Thread object
  • The third step is to start the thread again by calling the start() method of the thread object
Class ThreadRunnable implements Runnable{@override public void run() {system.out.println (" implements Runnable; + Thread.currentThread().getName()); } } class Main{ public static void main(String[] args) { ThreadRunnable runnable = new ThreadRunnable(); Thread thread = new Thread(runnable); thread.start(); }}Copy the code

3. Create threads using Callable and Future

  • Create an implementation class for the Callable interface and implement a call() method that will be the thread body and return no value. Create an instance of the Callable implementation class. (starting with java8, you can create Callable objects directly using Lambda expressions.)
  • The Callable object is wrapped with a FutureTask class that encapsulates the return value of the Callable object’s call() method.
  • Create and start a new Thread using FutureTask as the target of the Thread object.
  • Call the Get method of the FutureTask object to get the return value after the child thread completes execution.
class ThreadCallable implements Callable<String>{ @Override public String call() throws Exception { System.out.println(" implement Callable interface, override call method create thread; "+ thread.currentThread ().getName()); Return "return thread Call"; } } class Main{ public static void main(String[] args) throws ExecutionException, InterruptedException { //FutureTask futureTask = new FutureTask((Callable) new ThreadRunnable()); Java8 Lambda expression FutureTask<String> FutureTask = new FutureTask<String>(new ThreadCallable()); Thread thread = new Thread(futureTask); thread.start(); System.out.println(futureTask.get()); //Lambda FutureTask<Integer> task = new FutureTask<Integer>((Callable<Integer>)()->{ int i = 0; for (; i<10; i++){ System.out.println(Thread.currentThread().getName()+"===="+i); } return i; }); new Thread(task).start(); System.out.println(task.get()); }}Copy the code

4. Using thread pools for example using the Executor framework (consisting of three main parts)

1. A task provides the Runnable or Callable interface required for executing a task. Runnable interface or Callable interface implementation class can be ThreadPoolExecutor or ScheduledThreadPoolExecutor execution. The Runnable interface does not return results, but the Callable interface does. The following introduces some methods for Executors to switch between the two. The following figure shows the tasks to be executed, including Executor, the core task execution interface, and ExecutorService interface inherited from Executor. ScheduledThreadPoolExecutor and ThreadPoolExecutor these two key class implements the ExecutorService interface.

3. Obtain the resulting Future interface and its implementation class, FutureTask. When we put the Runnable interface or Callable interface implementation class (call the submit method) to ThreadPoolExecutor or ScheduledThreadPoolExecutor, returns a FutureTask object.

A diagram of the Executor framework

1. The main thread first creates a task object that implements the Runnable or Callable interface. 2. You can direct the created Runnable object to the ExecutorService and perform 3. If executorService.submit (…) ExecutorService will return an object that implements the Future interface. Finally, the main thread can execute the futureTask.get () method to wait for the task to complete. The main thread can also cancel this task by executing futureTask.cancel (Boolean mayInterruptIfRunning).

The five states of Thread

Create, Ready, Run, suspend (including blocking, sleeping, waiting), end

  1. New state (New) : A New thread object is created.
Threadt1 = new Thread(() -> {system.out.println ("t1"); }, "t1");Copy the code
  1. Ready state (Runnable) : After a thread object is created, another thread calls the start() method of that object. The thread in this state is in the runnable thread pool and becomes runnable, waiting to acquire CPU usage.
Threadt2 = new Thread(() -> {system.out.println ("t2 run"); }, "t2"); t2.start();Copy the code
  1. Running: A thread in the ready state retrieves the CPU and executes program code.
Threadt2 = new Thread(() -> {while (true) {system.out.println ("t2 run"); } }, "t2"); t2.start();Copy the code
  1. Blocked: THE Blocked state is when a thread gives up CPU usage for some reason and temporarily stops running. Until the thread enters the ready state, it has no chance to go to the running state. There are three types of blocking:

    Wait blocking: A running thread executes wait(), and the JVM places that thread into the wait pool. (2) Synchronous blocking: When a running thread acquires a synchronized lock on an object, if the lock is occupied by another thread, the JVM adds that thread to the lock pool. Other blocking: When a running thread executes a sleep() or join() method, or makes an I/O request, the JVM puts the thread in a blocked state. When the sleep() state times out, when the join() wait thread terminates or times out, or when I/O processing is complete, the thread goes back to the ready state.Copy the code
TIMED_WAITING Thread t3 = new Thread(() -> {synchronized (threadStatedemo.class) {try {// The bottom of TimeUnit is also called thread.sleep () on timeunit.seconds.sleep (5000); } catch (InterruptedException e) { e.printStackTrace(); } } }, "t3"); t3.start(); //WAIT join() WAIT Thread t4 = new Thread(() -> {try {t2.join(); } catch (InterruptedException e) { e.printStackTrace(); } }, "t4"); t4.start(); T5 = new Thread(() -> {synchronized; t5 = new Thread(() -> {synchronized (ThreadStateDemo.class) { log.info("BLOCKED..." ); } }, "t5"); t5.start(); // The thread has completed execution. T6 = new Thread(() -> {log.info(" one line "); }, "t6"); t6.start();Copy the code
  1. Dead: a thread terminates its life cycle when it finishes executing or exits the run() method due to an exception.

Third, Thread method

1.sleep

Sleep for a few seconds and free up the CPU for someone else to execute.

2.yield

Let the CPU briefly, who can grab the execution, not grab the original execution.

3.join

There are two threads, AB. At some point thread A calls join(thread B), at which point thread A sleeps until thread B finishes executing and thread A continues executing. Join yourself.

4.getState

Get the thread state, a total of six: