java thread implementation

java thread implementation

First of all, single thread can be understood as one person, and multi thread can be understood as many persons. Generally, it takes less time for a task to be assigned to multiple persons than to be assigned to one person. So java multithreading is to work faster and save time.

Two ways to create java threads

Inherit Thread class

The only way to start a Thread is through the start() instance method of the Thread class. The start() method is a native method, which will start a new Thread and execute the run() method

The following code

package com.rookie.bigdata.thread;


/**

 * @author rookie

 * @version 1.0

 * @date 2020/3/19 21:16
   */
   public class MyThread extends Thread {

   private String name;

   public MyThread(String name) {
       this.name = name;
   }

   @Override
   public void run() {
       for (int i = 0; i < 100; i++) {
           System.out.println("implement " + i + name);
           try {
               Thread.sleep(100);
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
       }
   }

   public static void main(String[] args) {
       MyThread thread1 = new MyThread("thread1");
       thread1.start();

       MyThread thread2 = new MyThread("thread2");
       thread2.start();

   }

}

Implement the Runnable interface

Another way is to implement the Runnable interface

package com.rookie.bigdata.thread;

/**

 * @author rookie

 * @version 1.0

 * @date 2020/3/19 21:23
   */
   public class MyRunnable implements Runnable {

   private String name;

   public MyRunnable(String name) {
       this.name = name;
   }

   @Override
   public void run() {
       for (int i = 0; i < 100; i++) {
           System.out.println("implement " + i + name);
           try {
               Thread.sleep(100);
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
       }
   }

   public static void main(String[] args) {
       MyRunnable runnable1 = new MyRunnable("runnable1");
       Thread thread1 = new Thread(runnable1);
       thread1.start();

       MyRunnable runnable2 = new MyRunnable("runnable2");
       Thread thread2 = new Thread(runnable2);
       thread2.start();


    }

}

Implement Callable interface

The Callable interface is more powerful than the above two types, as follows

package com.rookie.bigdata.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**

 * @author rookie

 * @version 1.0

 * @date 2020/3/19 21:56
   */
   public class MyCallable implements Callable {
   private String name;

   public MyCallable(String name) {
       this.name = name;
   }

   @Override
   public Object call() throws Exception {
       for (int i = 0; i < 100; i++) {
           System.out.println("Execution thread" + i + name);
           try {
               Thread.sleep(100);
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
       }
       return "task";
   }

   public static void main(String[] args) throws ExecutionException, InterruptedException {
       MyCallable myCallable=new MyCallable("callabe");
       FutureTask futureTask=new FutureTask(myCallable);
       Thread thread=new Thread(futureTask);
       thread.start();

       System.out.println(futureTask.get());
       System.out.println("Execute main thread");

   }

}

When the Callable interface is implemented, if the futureTask.get() method is invoked in the boot thread, the startup thread will wait for the thread to be executed before starting the thread to execute other processes.

Thread life cycle

When a thread is not created and started, it either enters the execution state immediately or is not always in the execution state. In the life cycle of a thread, it needs to go through five states: new, ready, running, Blocked and dead. Especially when the thread starts, it does not occupy the CPU all the time. The CPU switches between multiple threads, so the thread state will switch between running and blocking many times

New (New)

When the program uses new to create a thread, the thread is in the new state,

Ready (Runnable)

When the thread object calls the start() method, the thread is ready.

Running status

If the ready thread gets the CPU and starts executing the thread body of the run() method, the thread is running.

Blocked status

Blocking state means that the thread has given up the CPU usage right for some reason, that is to say, it has given up the CPU timeslice and temporarily stopped running. Until the thread enters the runnable state, there is no chance to get the CPU timeslice again to the runnable state. There are three types of congestion:

1. Wait for blocking (o.wait - > wait queue): the running thread executes the o.wait() method, and the JVM will put the thread into the wait queue

2. Synchronization block: when a running thread acquires the synchronization lock of an object, if the synchronization lock is occupied by another thread, the JVM will put the thread into the lock pool.

3. Other blocking (sleep/join): when a running thread executes the sleep or join method, or issues an I/O request, the JVM will set the thread to blocking state. When the sleep() state times out, the join() waits for the thread or times out, or the I/O processing is completed, the thread will return to the runnable state.

Thread dead

Thread death mainly includes the following three ways:

1. Normal end: the execution of run() or call() method is completed, and the thread ends normally.

2. Exception end: the thread throws an exception or Error.

3. Call stop: directly call the thread's stop() method to end the thread.

Related source code reference: https://github.com/albert-liu435/rookies-javases/tree/master/rookie-javase-thread

Tags: Java jvm less github

Posted on Sun, 22 Mar 2020 06:50:46 -0400 by kyoru