当前位置:网站首页>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
边栏推荐
- 负载均衡器
- 建设星际计算网络的愿景
- The El tree implementation only displays a certain level of check boxes and selects radio
- Redis master-slave replication process
- 通过 PDO ODBC 将 PHP 连接到 MySQL
- 大型互联网为什么禁止ip直连
- s16. One click installation of containerd script based on image warehouse
- 【递归之数的拆分】n分k,限定范围的拆分
- 使用 Bitnami PostgreSQL Docker 镜像快速设置流复制集群
- 携号转网最大赢家是中国电信,为何人们嫌弃中国移动和中国联通?
猜你喜欢
随机推荐
多级缓存使用
Independent operation smart farm Innovation Forum
PHP PDO ODBC将一个文件夹的文件装载到MySQL数据库BLOB列,并将BLOB列下载到另一个文件夹
MetaLife与ESTV建立战略合作伙伴关系并任命其首席执行官Eric Yoon为顾问
Calculate the number of occurrences of a character
Cap theorem
什么是CNAS认证?CNAS认可的软件测评中心有哪些?
[leetcode daily question] install fence
Multi level cache usage
Do we media make money now? After reading this article, you will understand
Rsync + inotify remote synchronization
Connect PHP to MSSQL via PDO ODBC
How do you think the fund is REITs? Is it safe to buy the fund through the bank
Temporal model: long-term and short-term memory network (LSTM)
c语言---字符串+内存函数
Basic concepts of website construction and management
Load Balancer
Deletes the least frequently occurring character in the string
一刷314-剑指 Offer 09. 用两个栈实现队列(e)
王启亨谈Web3.0与价值互联网“通证交换”