Java multi-thread

About memory

Each thread has its own thread stack, that is, variables can’t be shared, they can only be copied by value and everything new from each thread is stored in the heap, all shared

The life cycle of a thread

A thread has five states: New, ready, Running, blocked, and dead. When a thread is new, the JVM allocates memory for it and initializes the values of its member variables. When the thread calls the strat() method, the thread is ready to create a method call stack and a program counter for it.

The method call stack is the place where the program counter stores the next unit instruction, which counts the number of method calls

Run; The ready state obtains the CPU and starts executing the run() method blocking: for example, entering an I/O operation

New, ready

When a thread is created using the new keyword, it is in the newly created state, just like any Other Java thread, and is allocated memory by the Java virtual machine, initializing the values of the variable members.

Running and blocking

Thread scheduling

Preemptive scheduling for desktops and servers, collaborative scheduling for small devices,

Thread block

The thread actively gives up occupied processor resources using the sleep() method. The thread calls the blocking I/O method and waits for the notification thread to call suspend() before the method is returned

unblocked

Depending on the corresponding can

Thread priority

Normal 5, low 1, high 10 default 5

About start and run

Start creates a thread that runs in a time slice. The start method creates a thread and the run method runs the thread.

Create a thread

Create a Thread using the Thread inheritance class

Document docs.oracle.com/javase/8/do… The class must override the run method. Is the entry point for the new thread. You must call the start() method to run.

Is essentially an implementation of the Runnable interface

package demo2;

public class testPublic static void main(String[] args) {// Create a thread ThreadDemo run1 = new ThreadDemo(); run1.start(); // After the thread is run, the JVM will call the run method from time to time to run}}Copy the code
package demo2;

public class ThreadDemo extends Thread{
	public ThreadDemo() {
		System.out.println("hello world");
	}
	
	public void run() {
		System.out.println("Thread entry");
		for(int i = 0; i > 10; i++) {
			System.out.println("Output content");
		}
		System.out.println("Thread completes execution"); }}Copy the code

In fact, the start method of the parent class can also be overridden

package demo2;

public class ThreadDemo extends Thread{
	public ThreadDemo() {
		System.out.println("hello world");
	}
	
	public void run() {
		System.out.println("Thread entry");
		for(int i = 0; i > 10; i++) {
			System.out.println("Output content");
		}
		System.out.println("Thread completes execution");
	}
	
	public void start() {
		System.out.println("Start thread"); this.run(); }}Copy the code

And then test the class

package demo2;

public class testPublic static void main(String[] args) {// Create a thread ThreadDemo run1 = new ThreadDemo(); run1.start(); // Start thread}}Copy the code

Thread method

public final void setDaemon(boolean on)

Used to mark daemons and user threads User threads, a normal thread daemons that are normally created to serve user threads without requiring upper-level calls, such as gc garbage collection as an obvious daemon thread, mysql also has threads that perform scheduled tasks.

Interrupt threads

It indicates that a thread is interrupted and an error is thrown.

Use the Runnable interface

Document https://docs.oracle.com/javase/8/docs/api/ belongs to Java. Lang, bags, for automatic default loading method of the interface has a run run method for entry of the program Threads must be started by the Thread class constructor

package demo2;

public class testPublic static void main(String[] args) {demoRunnable r1 = new demoRunnable(); // Pass in the Thread constructor, name it, and run new Thread(r1,"name").start(); // After the thread is created, call start thread}}Copy the code
package demo2; public class demoRunnable implements Runnable{ private int i; // The thread below is running @override public voidrun() {
		for(int i = 0; i < 100; i++) {
			System.out.println("Running thread"+ i); }}}Copy the code

Threads are created through Callable and Future

Use Callable to create an interface implementation class interface source below

@FunctionalInterface
public interface Callable<V> {
    V call() throws Exception;
}
Copy the code

Implements a generic type that returns the type and needs to implement the Call method. Using wrapped objects

For wrapper type, that is, wrapping something that is not an object into an object, for wrapper type, implements the type of the object, as a class

The Callable interface is implemented first, where the Call class is the body of the child thread of the program

package demo2;

import java.util.concurrent.Callable;

public class CallableDemo implements Callable<Integer>{
	@Override
	public Integer call() throws Exception {
		System.out.println("Start running a thread");
		for(int i = 1, i < 10; i++) {
			System.out.println("Running"); } // block the Thread thread.sleep (200);return1; // Return the thread value}}Copy the code

The Future object is then created, which will be used to start the child thread

package demo2;

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

public class testPublic static void main(String[] args) {CallableDemo CTT = new CallableDemo(); FutureTask<Integer> ft = new FutureTask<>(ctt); // This method sets new Thread(ft,"Return result value").start(); try { System.out.println(ft.get()); } catch (InterruptedException | ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); }}}Copy the code
package demo2;

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

public class CallableDemo implements Callable<Integer>{
	@Override
	public Integer call() throws Exception {
		System.out.println("Start running a thread");
		for(int i = 1; i < 10; i++) {
			System.out.println("Running");
		}
		return1; // Return the thread value}}Copy the code