current position:Home>Roommate hit the king and learned Java multithreading..

Roommate hit the king and learned Java multithreading..

2022-01-27 04:39:59 Silent King II

about Java For beginners , Many of the concepts of multithreading sound difficult to understand . For example :

  • process , Is the encapsulation of the runtime program , It is the basic unit of resource scheduling and allocation in the system , The concurrency of the operating system is realized .
  • Threads , Is a subtask of a process , yes CPU Basic unit of dispatch and dispatch , It realizes the concurrency within the process .

Very abstract , Isn't it ? Make a comparison , You're beating the king ( Actually, I can't play doge):

  • The process can be compared to the game you played
  • Threads can be compared to heroes of your choice or crystal monsters in the game .

Take this metaphor to understand the relationship between process and thread , A process that can have multiple threads is called multithreading . Does it feel very easy to understand ?

1、 The thread is under the process

( A separate hero 、 Wild monster 、 Small soldiers certainly can't run )

2、 Processes don't interact with each other , The end of the main thread will lead to the end of the whole process

( There will be no connection and influence between the two games . Your crystal was pushed away , Your game is over )

3、 Different process data is difficult to share

( It's hard to connect between the two games , Related situations, such as the enemy of the upper hand, which is matched to )

4、 Data can be easily shared between different threads in the same process

( The game you played , You can see the status of each player —— Life and death , You can also see the output of each player and so on )

5、 The memory address used by the process can limit the usage

( Open room mode , Determines how many people you can set to enter , When the room is full , No one else can get in , Unless someone leaves the room , Other talents can enter )

After understanding the above concepts , Let's look at two ways to create multithreads :

①: Create a class inheritance Thread class , And rewrite run Method .

public class MyThread extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println(getName() + ": I hit " + i + " A little soldier ");
        }
    }
}

Let's write a test method to verify :

// establish MyThread object 
MyThread t1=new  MyThread();
MyThread t2=new  MyThread();
MyThread t3=new  MyThread();
// Set the name of the thread 
t1.setName(" ruban ");
t2.setName(" Liu bei ");
t3.setName(" Arthur ");
// Start thread 
t1.start();
t2.start();
t3.start();

Let's take a look at the results after implementation :

②: Create a class implementation Runnable Interface , And rewrite run Method .

public class MyRunnable implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            try {//sleep An exception will occur to show the processing 
                Thread.sleep(20);// Pause 20 millisecond 
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " I hit :" + i + " A little soldier ");
        }
    }
}

Let's write a test method to verify :

// establish MyRunnable class 
MyRunnable mr = new MyRunnable();
// establish Thread Parametric construction of class , And set the thread name 
Thread t1 = new Thread(mr, " Zhang Fei ");
Thread t2 = new Thread(mr, " The sable cicada ");
Thread t3 = new Thread(mr, " Lyu3 bu4 ");
// Start thread 
t1.start();
t2.start();
t3.start();

Let's take a look at the results after implementation :

1、 Why rewrite run Method ?

because run Method is used to encapsulate the code executed by the thread .

2、run() Methods and start() What's the difference ?

  • run(): Encapsulating code executed by threads , A direct call is equivalent to calling a normal method .
  • start(): Start thread , Then from JVM Calling the run() Method .

3、 By inheritance Thread Method and implementation of Runnable Interface way to create multithreading , Which good ?

Realization Runable Good interface , There are two reasons :

  • ①、 Avoided Java Limitations of single inheritance
  • ②、 It is suitable for multiple same program codes to deal with the same resource , Thread 、 Effective separation of code and data , More in line with the object-oriented design idea .

For thread control , You will also encounter 3 There are two common ways , Let's introduce them one by one .

1)sleep(): Pauses the currently executing thread for the specified number of milliseconds , That is, go into sleep .

It should be noted that ,sleep The exception should be handled when .

try {//sleep An exception will occur to show the processing 
    Thread.sleep(20);// Pause 20 millisecond 
} catch (InterruptedException e) {
    e.printStackTrace();
}

2)join(): Wait for this thread to finish executing before it's turn for subsequent threads to get cpu The enforcement of , Using this also throws an exception .

// establish MyRunnable class 
MyRunnable mr = new MyRunnable();
// establish Thread Parametric construction of class , And set the thread name 
Thread t1 = new Thread(mr, " Zhang Fei ");
Thread t2 = new Thread(mr, " The sable cicada ");
Thread t3 = new Thread(mr, " Lyu3 bu4 ");
// Start thread 
t1.start();
try {
    t1.join(); // wait for t1 It's only after execution that it's your turn t2,t3 rob 
} catch (InterruptedException e) {
    e.printStackTrace();
}
t2.start();
t3.start();

Let's take a look at the results after implementation :

3)setDaemon(): Mark this thread as a guardian thread , To be precise , Is to serve other threads , image Java Garbage collection thread in , Is a typical daemon thread .

// establish MyRunnable class 
MyRunnable mr = new MyRunnable();
// establish Thread Parametric construction of class , And set the thread name 
Thread t1 = new Thread(mr, " Zhang Fei ");
Thread t2 = new Thread(mr, " The sable cicada ");
Thread t3 = new Thread(mr, " Lyu3 bu4 ");

t1.setDaemon(true);
t2.setDaemon(true);

// Start thread 
t1.start();
t2.start();
t3.start();

If all other threads have finished executing ,main Method ( The main thread ) It's done ,JVM You're going to quit , That is, stop running . If JVM It's all down , The daemon thread naturally stops .

Finally, let's take a look at the thread life cycle , A picture is worth a thousand words .

The idea and most of the content of this article come from iron powder Hold for a long time , It's very interesting , ha-ha . The second brother made some adjustments , Hope to give beginners Java Multithreaded little partner, a little help and inspiration .

by the way , This article has been included in 《Java The road to advancement of programmers 》 Columnar 「 Concurrent programming 」 piece , The column is in GitHub The harvest has been 832 Mei xingbiao :

https://github.com/itwanger/toBeBetterJavaer

I hope more and more Java Enthusiasts can benefit from this open source project , and More and more people are star, It will also inspire me to create better content ~

copyright notice
author[Silent King II],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201270439569627.html

Random recommended