cool hit counter J2SE Fast Forward】--Java Multithreading Mechanism_Intefrankly

J2SE Fast Forward】--Java Multithreading Mechanism


Copyright: This is an original post by the blogger and may not be reproduced without the blogger's permission. https://blog.csdn.net/huyuyang6688/article/details/44056119

When learning about threads in Java, it was natural to associate it with the processor piece of the operating system that I had learned before.

meaning

The article begins with a general statement about the concepts of programs, processes and threads and the relationship between them.

Program: A program is a static piece of code, or an executable program.

Process: A process is a dynamic execution of a program, which corresponds to a dynamic execution process from the loading, running and ending of the code.

Thread: a smaller unit of execution than a process, a process can spawn multiple threads, or branches, during its execution. It is the smallest unit of program execution flow.

Come see a small program.

public class Test {
	public static void main(String[] args) {
		fun1();
	}
	public static void fun1(){
		System.out.println(fun2()+fun3());		
	}
	public static String fun2(){
		return "Hello ";
	}
	public static String fun3(){
		return "World!";
	}
}

It is executed in the following order. In the main method, the execution from ① to ⑥ is one thread, and there is no branching, which is one thread.

Implementation of threads

When the JVM executes to the main method, it starts a thread, called the main thread. If other threads are also created in the main method, then the JVM switches between the main thread and the other threads on a rotating basis, ensuring that each thread has access to CPU resources.

Threads in Java are implemented through the java.lang.Thread class, and each Thread object represents a new thread.

There are two ways to implement threads in Java.

1. Inherit Thread class and override its run method (to encapsulate the commands to be executed by the entire thread) and call the start method to start the thread.

For example, if the following class T were to implement threads, the code would be as follows.

public class CreateThreadTest{
	public static void main(String[] args) {
		T r=new T();
 		r.start();    /T class threads start execution
		for(int i=0;i<100;i++)
		{
			System.out.println("The main thread is executing~~~~"+i);
		}
	}
}
class T extends Thread
{
 	public void run(){// override the run method in the parent class
		for(int i=0;i<100;i++)
		{
			System.out.println(" The thread I created is executing~~~~"+i);
		}
	}
}

Now, this one little program has a total of two threads being executed, one for the main thread and one for the thread created by the T class.

2、Implementation of Runnable interface

Another way to do this is to have the class that implements the thread implement the Runnable interface, implement the only method in the Runnable interface, run(), and then create the thread object by using an instance of such as an argument to the constructor of the Thread class.

For example, the above example could also be written like this.

public class CreateThreadTest {
	public static void main(String[] args) {
		T r=new T();
 		Thread t=new Thread(r);     // Create the thread object
 		t.start();     //T class threads start
		for(int i=0;i<100;i++)
		{
			System.out.println("The main thread is executing~~~~"+i);
		}
	}
}
class T implements Runnable 
{
	public void run(){
		for(int i=0;i<100;i++)
		{
			System.out.println(" The thread I created is executing~~~~"+i);
		}
	}
}

The essence of both methods is that both require overriding the run method, and both end up with the Thread class' start method starting the thread.

Warm tip: Because multiple inheritance is not supported in Java, when implementing threads, once you inherit from the Thread class, you can't inherit from other classes. However, Java supports the implementation of multiple interfaces, so the second middle method is recommended and is more flexible.

multi-threaded

Multithreading is primarily intended to synchronize multiple tasks, i.e., to execute multiple threads at the same time. Multithreading divides a process into multiple tasks that work independently of each other

We all know that most operating systems such as Windows, Mac OS X, Unix, Linux, etc., nowadays support multi-threading, but what we usually call multi-threading does not mean that the CPU will process multiple threads at the same time, each CPU will only process one thread at the same point in time, except that it is so fast and the processing time is so extremely short that we can think of it as being able to process multiple threads at the same time. So only if your machine is "dual-core" or even "multi-core" can you achieve true multithreading.

See below for an example of multi-threading.

Execution of two threads t1 and t2

public class ThreadTest {
	public static void main(String[] args) {
		Thread t1=new Thread(new T1());
		Thread t2=new Thread(new T2());
		t1.start();t2.start();
	}	
}
class T1 implements Runnable{
	public void run(){
		for(int i=0;i<10;i++){
			System.out.println(" threads1 Implementation is in progress------"+i);
			if(i==9){
				System.out.println(" threads1 Implementation has been completed------"+i);
				break;
			}
		}
	}
}
class T2 implements Runnable{
	public void run(){
		for(int i=0;i<10;i++){
			System.out.println(" threads2 Implementation is in progress------"+i);
			if(i==9){
				System.out.println(" threads2 Implementation has been completed------"+i);
				break;
			}
		}
	}
}

Before you look at the results below, use your brain to think about what the results should look like~~

Implementation results.

Is it different from what you predicted? If threads were not added, the result would have been that thread 1 would have been executing for the first ten lines, and thread 2 would have started executing only after thread 1 was finished. The thread scheduling algorithm makes each thread execute for a while and enter a wait state before executing another thread.

Commonly used methods in threads

If one tries this example above by hand, one will find that the two threads t1 and t2 are uncertain and uncontrollable in terms of who executes first, who executes second, who executes for how long, etc. Here are just a few of the methods that are commonly used in threads.

★ void yield() method

In a thread that executes to the yield() method, that thread gives up CPU resources, suspending the currently executing thread object and allowing the CPU to execute other threads with the same priority. A good example of threads being happy to be humble!

Example.i The value of the0 up to99, Output the name of the thread instance each time, properi be10 multiple of, executeyield approach。

 public class TestYield {
	public static void main(String[] args) {
		MyThread thread1=new MyThread("thread1");
		MyThread thread2=new MyThread("thread2");
		thread1.start();thread2.start();
	}
}
class MyThread extends Thread{
	MyThread(String name){
		super(name);
	}
	public void run(){
		for(int i=0;i<100;i++){
			System.out.println(getName()+":"+i);
			if(i%10==0){
				yield();
			}
		}
	}
}

As can be seen from the first few outputs in the results, for thread1, whenever i is a multiple of 10, the process gives way and the thread2 process executes; the same is true for thread2: the

Note: The yield() method will switch the currently running thread to a runnable state, but it may not have an effect because in practice the thread executing the yield method may still be selected again by the scheduler.

★ void sleep(long millis) method and void sleep(long millis,int nanos)

Lets the thread sleep (suspend execution) for the specified length of time; the parameter millis is in milliseconds and the parameter nanos is in nanoseconds. A thread enters a blocking state after executing the sleep method, and after the specified time period has elapsed, the thread enters an executable state and waits to be scheduled by the operating system.

Example.

import java.util.*;
public class TestSleep {
	public static void main(String[] args)
	{
		MyThread thread=new MyThread();
		thread.start();
	}
}
class MyThread extends Thread
{
	public void run()
	{
		while(true)
		{
			System.out.println("==="+new Date()+"===");
			try{
				sleep(1000);
			}catch(InterruptedException e){
				return;
			}
		}
	}
}

You should have guessed the result after reading the code, the current time is output every second, which is equivalent to a timer. There are two threads in this program, the main thread (i.e. main method) has no other tasks to execute after the thread thread, so it can be seen as only executing the thread thread, if you remove the sleep method in the example, then it will "swish swish swish" and output the current time (your CPU fan will also "swish swish" ~~~~).

★voidjoin() approach

It says that when a thread executes the yield method, it automatically gives up CPU resources, converting the state from running to runnable. The join() method can be said to be exactly similar, when a thread executes the join method then it will keep executing until that thread ends.

Still, to illustrate.

public class TestJoin {  
    public static void main(String[] args) throws InterruptedException {  
        Thread t1 = new Thread(new ThreadA());  
        Thread t2 = new Thread(new ThreadB());  
        t1.start();  
         t1.join();  // After the t1 thread starts executing, it will continue until the t1 thread ends, otherwise it will never give up the CPU  
        t2.start();  
         t2.join();  // Once thread t2 starts executing, it will continue until thread t1 finishes, otherwise it will never give up the CPU  
    }  
}
class ThreadA implements Runnable {   
    public void run() {  
        for (int i=0;i<10;i++) {  
            System.out.println("A The thread is running.~~~~" + i);  
        }   
    }  
}   
class ThreadB implements Runnable {   
	public void run() {  
        for (int i=0;i<10;i++) {  
            System.out.println("B The thread is running.~~~~" + i);  
        }   
    }   
} 

Let's imagine for a moment that the two threads joining t1 and t2 start without executing the join method, then the CPU does not necessarily allocate the same execution time and order to them, as in the figure below left; if t1 and t2 execute the join method, then once they start, they will execute to the end, as in the figure below right.

Why use multiple threads

One last question, why use multiple threads?

I saw a great analogy in the forums: a single thread is when the bully boss does it all by himself from start to finish, and another thread is when the boss breaks out a thing and tells a junior to do it, and that junior's entry speeds up the whole thing, but sometimes it can get in the way of doing it.

Of course, to understand the essence of multithreading more deeply, it is not enough to learn the theory, it is more important to dig and think in practice and projects.


Recommended>>
1、Amoy News
2、What are the top three exhibits and top ten categories of interest The big data of the first Fair is here
3、This Weeks Student Work Appreciation Programming Class Premiere
4、The QR code around you do you really know it
5、Lv Zhan How will we respond in the age of artificial intelligence

    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号