当前位置:网站首页>Thread Basics
Thread Basics
2022-07-05 03:38:00 【Data ape vision】
Foreword and outline
Every process in the computer system (Process) All represent a running program , A process is an encapsulation of a runtime program , The basic unit of resource scheduling and allocation in the system .
There can be many threads in a process , A thread is a subtask of a process , yes CPU Basic unit of dispatch and dispatch , It is used to ensure the real-time performance of the program , Achieve concurrency within the process , Threads are also the smallest execution and scheduling unit recognized by the operating system .
stay Java Threads are the carrier of program execution , The code we write is run by threads . Sometimes in order to increase the efficiency of program execution , We have to use multithreading for programming , Although multithreading can maximize program utilization CPU The efficiency of , But it is also the frequent occurrence of procedural accidents 、 The biggest inducement for programmers to lose their hair . The main reason is that our thinking is single threaded by default , When writing multithreads, you have to switch , This requires us to have a thorough understanding of the basic knowledge of threading .
Let's summarize this article Java The foundation of threads , Master more , I'll lose less hair in the future , Not only save money for hair planting , Wages can still go up , This is a win-win situation . The outline of this paper is as follows :
OK, let's start today's text , Go straight to the code .
Java Thread in
up to now , All we wrote Java The program code is made up of JVM To create Main Thread In a single thread .Java Thread is like a virtual CPU, Can be run in Java In the application Java Code . When one Java When the application starts , Its entry method main() Method is executed by the main thread . The main thread (Main Thread) It's a by Java A special thread created by a virtual machine to run your application .
because Java It's all about objects , So threads are also represented by objects , Thread is a class java.lang.Thread Class or an instance of its subclass . stay Java Inside the application , We can go through Thread Instance creation and start more threads , These threads can execute the application code in parallel with the main thread .
Create and start threads
stay Java Create a thread , To create a Thread Class
Thread thread = new Thread();
To start a thread is to call the thread object start() Method
thread.start();
Of course , This example does not specify the code to be executed by the thread , So the thread will stop immediately after starting .
Specify the code to be executed by the thread
There are two ways to assign code to a thread to execute .
- The first is , establish Thread Subclasses of , Covering the parent class run() Method , stay run() Method to specify the code to be executed by the thread .
- The second is , Will implement Runnable (java.lang.Runnable) Is passed to Thread Construction method , establish Thread example .
Actually , There is a third usage , But on closer examination, it can be classified into the second kind of special use , Now let's look at the usage and differences of these three .
adopt Thread Subclasses specify the code to execute
By inheritance Thread Class to create a thread :
- Definition Thread Subclasses of classes , And cover the run() Method .run() The method body of the method represents the task to be completed by the thread , So the run Methods are called executors .
- establish Thread Instances of subclasses , The thread object is created .
- Calling the start Method to start the thread .
package com.learnthread;
public class ThreadDemo {
public static void main(String[] args) {
// Instantiate thread object
MyThread threadA = new MyThread("Thread Threads -A");
MyThread threadB = new MyThread("Thread Threads -B");
// Start thread
threadA.start();
threadB.start();
}
static class MyThread extends Thread {
private int ticket = 5;
MyThread(String name) {
super(name);
}
@Override
public void run() {
while (ticket > 0) {
System.out.println(Thread.currentThread().getName() + " Sold No " + ticket + " Tickets ");
ticket--;
}
}
}
}
The above procedure , The main thread starts the call A、B two-threaded start() after , Failed wait() Wait for their execution to end .A、B The execution body of two threads , Will be executed by the system concurrently , Wait until the thread ends directly , The program will exit .
By implementing Runnable Interface specifies the code to execute
Runnable In the interface , only one run() Method definition :
package java.lang;
public interface Runnable {
public abstract void run();
}
Actually ,Thread Class implements Runnable Interface . stay Thread Class overloaded constructor , Support receiving an implementation Runnale The object of the interface as its target Parameter to initialize the thread object .
public class Thread implements Runnable {
...
public Thread(Runnable target) {
init(null, target, "Thread-" + nextThreadNum(), 0);
}
...
public Thread(Runnable target, String name) {
init(null, target, name, 0);
}
...
}
By implementing Runnable Interface to create threads :
- Definition Runnable Interface implementation , Implement the interface run Method . The run The method body of a method is also the execution body of a thread .
- establish Runnable Instance of implementation class , And take this example as Thread Of target To create Thread object , The Thread Object is the real thread object .
- Calling the start Method to start the thread and execute .
package com.learnthread;
public class RunnableDemo {
public static void main(String[] args) {
// Instantiate thread object
Thread threadA = new Thread(new MyThread(), "Runnable Threads -A");
Thread threadB = new Thread(new MyThread(), "Runnable Threads -B");
// Start thread
threadA.start();
threadB.start();
}
static class MyThread implements Runnable {
private int ticket = 5;
@Override
public void run() {
while (ticket > 0) {
System.out.println(Thread.currentThread().getName() + " Sold No " + ticket + " Tickets ");
ticket--;
}
}
}
}
Running the above routine will produce the following output , Similarly, the program will exit after all threads are executed .
Runnable Threads -B Sold No 5 Tickets
Runnable Threads -B Sold No 4 Tickets
Runnable Threads -B Sold No 3 Tickets
Runnable Threads -B Sold No 2 Tickets
Runnable Threads -B Sold No 1 Tickets
Runnable Threads -A Sold No 5 Tickets
Runnable Threads -A Sold No 4 Tickets
Runnable Threads -A Sold No 3 Tickets
Runnable Threads -A Sold No 2 Tickets
Runnable Threads -A Sold No 1 Tickets
Process finished with exit code 0
Since it's for Thread Pass on Runnable The implementation object of the interface , In addition to the common way of defining classes to implement interfaces , We can also use anonymous classes and Lambda Expression Runnable The implementation of the .
- Use Runnable Anonymous classes are created as parameters Thread object :
Thread threadA = new Thread(new Runnable() {
private int ticket = 5;
@Override
public void run() {
while (ticket > 0) {
System.out.println(Thread.currentThread().getName() + " Sold No " + ticket + " Tickets ");
ticket--;
}
}
}, "Runnable Threads -A");
- Use to achieve Runnable Of Lambda Expressions are created as parameters Thread object :
Runnable runnable = () -> { System.out.println("Lambda Runnable running"); };
Thread threadB = new Thread(runnable, "Runnable Threads -B");
because ,Lambda It's stateless , Cannot define internal properties , Here is a simple example of printing one line of output , Just understand this usage .
边栏推荐
- The perfect car for successful people: BMW X7! Superior performance, excellent comfort and safety
- Machine learning experiment report 1 - linear model, decision tree, neural network part
- Ask, does this ADB MySQL support sqlserver?
- Class inheritance in C #
- SQL injection exercise -- sqli Labs
- What is the most effective way to convert int to string- What is the most efficient way to convert an int to a String?
- Hot knowledge of multithreading (I): introduction to ThreadLocal and underlying principles
- New interesting test applet source code_ Test available
- Anchor free series network yolox source code line by line explanation four (a total of ten, ensure line by line explanation, after reading, you can change the network at will, not just as a participan
- [learning notes] month end operation -gr/ir reorganization
猜你喜欢
[groovy] loop control (number injection function implements loop | times function | upto function | downto function | step function | closure can be written outside as the final parameter)
Huawei MPLS experiment
el-select,el-option下拉选择框
The architect started to write a HelloWorld
error Couldn‘t find a package.json file in “你的路径“
Tencent cloud, realize image upload
postman和postman interceptor的安装
Clickhouse物化视图
Multimedia query
Multi person online anonymous chat room / private chat room source code / support the creation of multiple chat rooms at the same time
随机推荐
[untitled]
Sqoop command
About authentication services (front and back, login, registration and exit, permission management)
【做题打卡】集成每日5题分享(第三期)
SQL injection exercise -- sqli Labs
SPI and IIC communication protocol
There is a question about whether the parallelism can be set for Flink SQL CDC. If the parallelism is greater than 1, will there be a sequence problem?
The perfect car for successful people: BMW X7! Superior performance, excellent comfort and safety
[web Audit - source code disclosure] obtain source code methods and use tools
[vérification sur le Web - divulgation du code source] obtenir la méthode du code source et utiliser des outils
Une question est de savoir si Flink SQL CDC peut définir le parallélisme. Si le parallélisme est supérieur à 1, il y aura un problème d'ordre?
[web source code code code audit method] audit skills and tools
有个疑问 flink sql cdc 的话可以设置并行度么, 并行度大于1会有顺序问题吧?
Difference between MotionEvent. getRawX and MotionEvent. getX
qrcode:将文本生成二维码
Google Chrome CSS will not update unless the cache is cleared - Google Chrome CSS doesn't update unless clear cache
Nmap使用手册学习记录
天干地支纪年法中为什么是60年一个轮回,而不是120年
Devtools的簡單使用
Pat class a 1162 postfix expression