Java thread: thread creation and startup, static proxy, Lambda expression

Posted by discorevilo on Tue, 08 Mar 2022 01:23:39 +0100

catalogue

preface

thread

Thread creation and startup

Inherit Java Lang.Thread class

Implement Runnable interface

Implement Callable interface

Static proxy

Lambda expression

Functional interface

last

preface

I don't know if you have ever thought about why so many people can play together at the same time when we play the glory of the king. We can see each other without affecting each other. This is related to multithreading. Today we'll learn about threading.

thread

The running application is called "process", and the control flow that can be executed independently in the process is called "thread". A process can be composed of multiple threads, which can perform different tasks, such as listening to sound, watching images, watching bullet screens, etc. at the same time in video.

  • Process is an execution process of execution program. It is a dynamic concept and the unit of system resource allocation;

  • Thread is the unit of CPU scheduling and execution. It is an independent execution path. There is at least one thread in a process, otherwise it has no meaning.

be careful:

  • Real multithreading refers to having multiple CPU s, that is, multiple cores. Many multithreads are simulated.

  • The running of threads is scheduled by the scheduler. The scheduler is related to the operating system, and the sequence can not be interfered by human beings;

  • Threads will bring additional overhead. Each thread interacts in its own working memory. Improper memory control will cause data inconsistency;

Thread creation and startup

When a JVM thread is created with the main() method, the JVM starts a process with the main() method.

There are three ways to create a Thread: inherit the Thread class, implement the Runnable interface and implement the Callable interface

The main methods of Thread class include:

methodfunction
start()Start thread
currentThread()Returns the currently running Thread object
run()Called by the scheduler, the thread stops when the run() method returns
sleep(int n)After n milliseconds of sleep, the thread runs again
setPriority(int p)Set thread priority
getPriority()Return thread priority
yield()Pauses the currently executing thread object and executes other threads
setName(String name)Give the thread a name
getName()Gets the string representing the thread name
stop()Stop thread execution

Inherit Java Lang.Thread class

Users can create an instance of the Thread class to create a new Thread, which will run concurrently with the main Thread. The subclass inherits the Thread class and has the ability of multithreading. The user Thread can be started by calling the start() method of the user Thread class.

Create steps:

  1. Declare a class and inherit Thread class;

  2. Rewrite the run() method and write the thread execution body;

  3. Create a thread object and call the start() method to start the thread.

For example:

public class first {
	static class Threadcase extends Thread{		//Create Threadcase class and inherit Thread
		public void run() {				       //Override the run() method
			System.out.println("Welcome to study Java thread !!!");
		}
	}
	public static void main(String[] args)throws Exception {
		Threadcase t=new Threadcase();			//Create Threadcase class instance object
		t.start();							  //Call the start() method to start the thread
        System.out.println("I'm the main thread");  
	}
}

The operation result is:

I'm the main thread
 Welcome to study Java thread !!!

be careful:

  • Running the above code many times will find that the running results will be different;

  • When there are many thread executors running, it will be found that the main thread and sub thread will execute alternately;

  • If you change the start() method to run() method, it will be executed according to the code sequence. You can try it yourself.

Implement Runnable interface

Due to the single inheritance limitation of Java, some classes must inherit some other classes and realize the characteristics of threads. At this time, this problem can be solved by implementing the interface Runnable. The interface has multithreading capability. The starting Thread is the incoming target object + Thread object start(). Create a Thread to declare the implementation class Runnable interface, and then override the run method. An instance of the class can then be assigned, passed as a parameter and started when the Thread is created.

Create steps:

  1. Define classes to implement Runnable interfaces;

  2. Rewrite the run() method and write the thread execution body;

  3. Create thread object;

  4. Create a Thread and pass it as a parameter. Call the start() method to start the Thread.

For example:

public class first {
	static class Threadcase implements Runnable{			  //Create a Threadcase class and implement the Runnable interface
		public void run() {									//Override the run() method
			System.out.println("Welcome to study Java thread !!!");
		}
	}
	public static void main(String[] args)throws Exception {   
		Threadcase t=new Threadcase();						 //Create implementation class object
		Thread thread=new Thread(t);						 //Create proxy class object
		thread.start();									    //Start thread
	}
}

The operation result is:

Welcome to study Java thread !!!

Note: lines 9 and 10 can be changed to:

new Thread(t).start();

Implement Callable interface

Since the Callable interface is rarely used, we only do a simple understanding of the implementation steps here. Interested students can write code for implementation by themselves. Create steps:

  1. To implement the Callable interface, the return value type is required;

  2. To rewrite the call method, you need to throw an exception;

  3. Create the target object;

  4. Create execution service: executorservice ser = executors newFixedThreadPool(1);

  5. Submit execution: future < Boolean > result1 = Ser submit(t1);

  6. Get result: Boolean R1 = result get();

  7. Shut down the server: Ser shutdownNow();

Static proxy

The word "agent" is familiar to everyone. It means that I can help you do something. For example, when we play the glory of the king, we sometimes ask others to score for ourselves. The last account that really scores is our own account. This is an agent.

  • Self: belong to the real role;

  • Acting role: acting for you and helping yourself score;

  • Upper division: it is enough to realize the upper division interface.

For example:

public class first {
	public static void main(String[] args){
		GameLeveing gameleveing=new GameLeveing(new My());		//Create an instance object of the GameLeveing class and use the My class
		gameleveing.agency();								  //Call the agency method
	}
}
interface Points{
	void agency();
}
class My implements Points{					//Create My class to implement the Points interface (real object, My own account should be on the glory king)
	public void agency() {					//Override the agency() method
		System.out.println("I'm the king of glory");
	}
}
class GameLeveing implements Points{		 //Create a GameLeveing class to implement the Points interface (proxy object to help you score)
	private Points target;					//Keyword target
	public GameLeveing(Points target) {		 //Pass the real object so that the real object can call the method of the proxy object
		this.target=target;					
	}
	public void agency() {					//Override the agency method
		before();
		this.target.agency();				//Real object
		after();
	}
	private void before() {					//Create private methods before and after
		System.out.println("Before scoring, log in to your account and play games");
	}
	private void after() {
		System.out.println("After the last minute, the final payment");
	}
}

The running result is:

Before scoring, log in to your account and play games
 I'm the king of glory
 After the last minute, the final payment

Note: both the real object and the proxy object should implement the same interface, and the proxy object should represent the real object.

Benefits of proxy: proxy objects can do many things that real objects can't do, and real objects can focus on doing their own things.

Lambda expression

In order to avoid too many definitions of anonymous internal classes, some meaningless code is removed, leaving only the core logic to make our code look very concise. We can use lambda expressions.

be careful:

  • lambda expressions can only be simplified into one line if there is only one line of code. If there are multiple lines, they are wrapped in code blocks;

  • The premise of using Lambda expression is that the interface is functional.

Functional interface

If any interface contains only one abstract method, it is a functional interface, for example:

interface like{
	void lambad();
}

For functional interfaces, we can create objects of the interface through Lambda expressions.

like l=()->{System.out.println("lkl");};
l.lambda();

In this way, you may not understand the benefits of using Lambda expressions. Let's understand them through two examples.

Example 1: Lambda expression is not used

public class first {
	public static void main(String[] args){
		nonuse no=new nonuse();           //Create a nonuse class instance object
		no.lambda(5);                     //Call lambda method
	}
}
interface like{                           //Create interface
	void lambda(int a);                   //Method of defining interface
}
class nonuse implements like{             //Create a nonuse class to implement the interface like
	public void lambda(int a) {           //Rewrite lambda method
		System.out.print(a);
	}
}

Example 2: using Lambda expressions

public class first {
	public static void main(String[] args){
		like l=(int a)->{System.out.println(a);};     //Using the like interface
		l.lambda(5);
	}
}
interface like{                    //Create like interface
	void lambda(int a);
}

The running results of the codes in the above two examples are the same. The running results are: 5

Lambda expression can be further simplified. The third line of code in example 2 can be simplified as:

   like l=(a)->{System.out.println(a);};
   like l=a->{System.out.println(a);};
or like l=a->System.out.println(a);;

Its operation results remain unchanged.

Note: when there are multiple parameters, the parameter type can also be removed, but to remove all parameter types, the parameters must be enclosed in parentheses.

last

Well, some knowledge about threads is here. Thank you for watching!!!

The next part continues to explain other knowledge of threads (thread state, thread synchronization, etc.)

Success is not something that will happen in the future, but something that will continue to accumulate from the moment you decide to do it.

Topics: Java Programming Multithreading