当前位置:网站首页>The principle and common methods of multithreading and the difference between thread and runnable
The principle and common methods of multithreading and the difference between thread and runnable
2022-04-23 15:45:00 【Have a drink together】
List of articles
Multithreading principle
Random printing
CPU There are two execution paths ,CPU You have a choice , It will be executed later main Method It will be executed later run Method .
It can also be said that two threads , One main Threads One run Threads Ask for CPU The enforcement of ( execution time ) Whoever grabs it will execute the corresponding code

Multithreaded memory diagram
- main Method to create an object , Create objects and store them in heap memory ( The address value is assigned to the variable name 0x11)
- mt.**run()** Invocation time run Methods are pushed into the stack It's actually a single threaded program (main Threads , It'll be done first run Method then executes other methods in the main thread )
- mt.**start()** When called, it will open up a new stack space . perform run Method (run The method is not in main Threads execute , Instead, execute in the new stack space , If it were start It will open up another stack space and another thread )
Yes cpu for ,cpu You have the right to choose It can be executed main Method 、 You can also perform two run Method .
The benefits of multithreading : When multithreading is executed , In stack memory , In fact, each execution thread has its own stack memory space , Multiple threads do not affect each other Stack pressing and spring stack .

Thread Common methods of class
Get thread name getName()
public static void main(String[] args) {
// establish Thread Subclass object of class
MyThread mt = new MyThread();
// call start Method , Start a new thread , perform run Method
mt.start();
new MyThread().start();
new MyThread().start();
// Chain programming
System.out.println(Thread.currentThread().getName());
}
/** Get the name of the thread : 1. Use Thread Methods in class getName() String getName() Returns the name of the thread . 2. You can get the currently executing thread first , Use methods in threads getName() Get the name of the thread static Thread currentThread() Returns a reference to the currently executing thread object . * @author zjq */
// Define a Thread Subclasses of classes
public class MyThread extends Thread{
// rewrite Thread Class run Method , Set up thread tasks
@Override
public void run() {
// Get thread name
//String name = getName();
//System.out.println(name);
// Chain programming
System.out.println(Thread.currentThread().getName());
}
}
Output is as follows :
main
Thread-2
Thread-0
Thread-1
Set the thread name setName() perhaps new Thread(“ Thread name ”)
-
Use Thread Methods in class setName( name )
void setName(String name) Change thread name , Make it and parameter name identical . -
Create a construction method with parameters , Parameter passing the name of the thread ; Call the parameter constructor of the parent class , Pass the thread name to the parent class , Let the parent class (Thread) Give the child thread a name
Thread(String name) Assign a new Thread object .
Code case :
// Enable multithreading
MyThread mt = new MyThread();
mt.setName(" cockroach ");
mt.start();
// Enable multithreading
new MyThread(" Wangcai ").start();
Pause the currently executing thread for the specified number of milliseconds sleep(long millis)
Code case :
public static void main(String[] args) {
// Analog stopwatch
for (int i = 1; i <=60 ; i++) {
System.out.println(i);
// Use Thread Class sleep How to make the program sleep 1 Second
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
🥧 The second way to create a multithreaded program - Realization Runnable Interface
Realization Runnable Interface to implement multithreading steps :
- Create a Runnable Implementation class of interface
- Override... In the implementation class Runnable Interface run Method , Set up thread tasks
- Create a Runnable Implementation class object of interface
- establish Thread Class object , Pass... In constructor Runnable Implementation class object of interface
- call Thread Class start Method , Start a new thread to execute run Method
The code case is as follows :
/** * 1. Create a Runnable Implementation class of interface * @author zjq */
public class RunnableImpl implements Runnable{
//2. Override... In the implementation class Runnable Interface run Method , Set up thread tasks
@Override
public void run() {
for (int i = 0; i <20 ; i++) {
System.out.println(Thread.currentThread().getName()+"-->"+i);
}
}
}
public static void main(String[] args) {
//3. Create a Runnable Implementation class object of interface
RunnableImpl run = new RunnableImpl();
//4. establish Thread Class object , Pass... In constructor Runnable Implementation class object of interface
Thread t = new Thread(run);// Print thread name
//5. call Thread Class start Method , Start a new thread to execute run Method
t.start();
for (int i = 0; i <20 ; i++) {
System.out.println(Thread.currentThread().getName()+"-->"+i);
}
}
Thread and Runnable The difference between
Realization Runnable Interface to create multithreaded programs :
- The limitation of single inheritance is avoided
A class can only inherit one class ( One can only have one father ), Class inherited Thread Class cannot inherit other classes .
Realized Runnable Interface , You can also inherit other classes , Implement other interfaces .
- Enhanced program scalability , Reduced program coupling ( decoupling )
Realization Runnable How to interface , The task of setting thread is separated from starting a new thread ( decoupling ).
In the implementation class , Rewrote run Method : Used to set thread tasks .
establish Thread Class object , call start Method : Used to start a new thread .
Start the thread with an anonymous inner class
Anonymous inner class start thread can simplify the coding of code .
The code case is as follows :
/** Anonymous inner class way to create threads anonymous : Isn't there a name Inner class : Classes written inside other classes Anonymous inner class functions : Simplify the code To inherit a subclass from a parent , Overrides the method of the parent class , Create subclass objects in one step Implement the class interface , Override methods in the interface , Create and implement class object composition in one step The end product of anonymous inner classes : Subclass / Implementation class object , And this class has no name Format : new Parent class / Interface (){ Repeat parent class / Methods in interfaces }; * @author zjq */
public class Demo01InnerClassThread {
public static void main(String[] args) {
// The parent class of the thread is Thread
// new MyThread().start();
new Thread(){
// rewrite run Method , Set up thread tasks
@Override
public void run() {
for (int i = 0; i <20 ; i++) {
System.out.println(Thread.currentThread().getName()+"-->"+" Zhan ");
}
}
}.start();
// Thread interface Runnable
//Runnable r = new RunnableImpl();// polymorphic
Runnable r = new Runnable(){
// rewrite run Method , Set up thread tasks
@Override
public void run() {
for (int i = 0; i <20 ; i++) {
System.out.println(Thread.currentThread().getName()+"-->"+" Threads ");
}
}
};
new Thread(r).start();
// The way to simplify the interface
new Thread(new Runnable(){
// rewrite run Method , Set up thread tasks
@Override
public void run() {
for (int i = 0; i <20 ; i++) {
System.out.println(Thread.currentThread().getName()+"-->"+"zjq");
}
}
}).start();
}
}
版权声明
本文为[Have a drink together]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231544553342.html
边栏推荐
- 【AI周报】英伟达用AI设计芯片;不完美的Transformer要克服自注意力的理论缺陷
- Why is IP direct connection prohibited in large-scale Internet
- Upgrade MySQL 5.1 to 5.67
- 考试考试自用
- Go language slice, range, set
- 携号转网最大赢家是中国电信,为何人们嫌弃中国移动和中国联通?
- Sorting and replying to questions related to transformer
- Upgrade MySQL 5.1 to 5.68
- 控制结构(一)
- Use bitnami PostgreSQL docker image to quickly set up stream replication clusters
猜你喜欢

IronPDF for . NET 2022.4.5455

Modèle de Cluster MySQL et scénario d'application

pgpool-II 4.3 中文手册 - 入门教程

KNN, kmeans and GMM

Mobile finance (for personal use)

考试考试自用

贫困的无网地区怎么有钱建设网络?

Why disable foreign key constraints

How did the computer reinstall the system? The display has no signal

What if the server is poisoned? How does the server prevent virus intrusion?
随机推荐
时序模型:门控循环单元网络(GRU)
Why disable foreign key constraints
Accumulation of applet knowledge points
What are the mobile app software testing tools? Sharing of third-party software evaluation
Best practices of Apache APIs IX high availability configuration center based on tidb
Go language, array, pointer, structure
字符串排序
Neodynamic Barcode Professional for WPF V11. 0
网站建设与管理的基本概念
Connect PHP to MSSQL via PDO ODBC
服务器中毒了怎么办?服务器怎么防止病毒入侵?
Go语言条件,循环,函数
移动app软件测试工具有哪些?第三方软件测评小编分享
IronPDF for .NET 2022.4.5455
Extract non duplicate integers
Go concurrency and channel
【AI周报】英伟达用AI设计芯片;不完美的Transformer要克服自注意力的理论缺陷
C language --- advanced pointer
码住收藏▏软件测试报告模板范文来了
shell脚本中的DATE日期计算