当前位置:网站首页>Use of multithreading
Use of multithreading
2022-06-12 15:18:00 【A_ M amu】
1. Threads
1、 What is thread ?
2. Why do I need threads ?
3. java How to implement multithreading ?
4. java The state of the thread in .
5. Some common methods in threads ?
6. Thread deadlock ?
2. What is thread ?
What is a process ?
1. Running programs . The basic unit of resources allocated by the system . If it's a single core cpu, Macroscopically, processes run in parallel , Microcosmic serial operation .
What is thread ?
Threads , Also known as lightweight process (Light Weight Process).
An execution path in the process , It's also CPU The basic dispatching unit of .
A process consists of one or more threads , Do different jobs with each other ,
At the same time , It's called multithreading .
3. Why multithreading is needed ?
In order to improve the cpu The usage rate of .

4.java How to implement multithreading ?
java There are three ways to implement multithreading ! 1.5
The first one is : By inheritance Thread class .
The second kind : Realization RUnnable Interface .
The third kind of : Realization Callable Interface .
4.1 Inherit Thead class .
1. Create a thread class and inherit Thread rewrite run Method .
2. stay main Method
3. Start thread start();
package demo01;
/**
* @program: Thread01
* @description:
* @author: Amur
* @create: 2022-01-04 09:05
**/
public class TestThread {
public static void main(String[] args) {
//③ Creating thread objects .
MyThread my=new MyThread();
// ④ Start thread ---- Automatically run Method
my.start();
for (int i = 0; i < 20; i++) { //my Threads main Threads
System.out.println("main======"+i);
}
}
}
//① Create class and inherit Thread class
class MyThread extends Thread{
//② rewrite run Method . The task code executed by the thread
@Override
public void run() {
for (int i = 0; i <20 ; i++) {
System.out.println("myThread========"+i);
}
}
}result :

The results of the analysis :

reflection : Can we control cpu What about the distribution of ?
1. You can't , because java The language cannot manipulate the underlying hardware .
4.2 Get and set the name of the thread
1. Get thread name
1. stay Thread In a subclass of this.getName()
2. Use Thread.currentThread().getName()
2. Set the name of the thread .
1. Through thread objects .setName()
2. By construction method
package demo01;
/**
* @program: Thread01
* @description:
* @author: Amur
* @create: 2022-01-04 09:05
**/
public class TestThread {
public static void main(String[] args) {
//③ Creating thread objects .
MyThread my=new MyThread(" Amur "); // The constructor names the thread
//my.setName(" Threads A"); // call setName() Set the thread name
// ④ Start thread ---- Automatically run Method
my.start();
//③ Creating thread objects .
MyThread my2=new MyThread(" Old wood ");
//my2.setName(" Threads B");
// ④ Start thread ---- Automatically run Method
my2.start();
}
}
//① Create class and inherit Thread class
class MyThread extends Thread{
public MyThread(String name){
super(name);
}
//② rewrite run Method . The task code executed by the thread
@Override
public void run() {
for (int i = 0; i <20 ; i++) {
// Get the name of the current thread this.getName() This class must be Thread Subclasses of .
// If the thread is not named, the default system will follow Thread-n To name 【n:0~】
// System.out.println(this.getName()+"========"+i);
//Thread.currentThread().getName() Can be used anywhere
System.out.println(Thread.currentThread().getName()+"========"+i);
}
}
}4.3 practice

package demo01;
/**
* @program: Thread01
* @description:
* @author: Amur
* @create: 2022-01-04 09:44
**/
public class TestTicket {
public static void main(String[] args) {
Ticket t1=new Ticket(" window A");
Ticket t2=new Ticket(" window B");
Ticket t3=new Ticket(" window C");
Ticket t4=new Ticket(" window D");
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class Ticket extends Thread {
private int ticket = 100;
Ticket(String name){
super(name);
}
@Override
public void run() {
while (true) {
if (ticket <= 0) {
break;
}
ticket--;
System.out.println(Thread.currentThread().getName() + " I bought one , The remaining :" + ticket + " Zhang ");
}
}
}
4.4 Create thread - Realization Runnable Interface .
package demo02;
/**
* @program: Thread01
* @description:
* @author: Amur
* @create: 2022-01-04 09:50
**/
public class TestRunable {
public static void main(String[] args) {
// Create thread task object
MyRunnable my1=new MyRunnable();
// Creating thread objects
Thread t1=new Thread(my1," Threads A"); //public Thread(Runnable target,String name)
t1.start();
// Creating thread objects
Thread t2=new Thread(my1," Threads B"); //public Thread(Runnable target,String name)
t2.start();
}
}
class MyRunnable implements Runnable{
@Override
public void run() { // The task code executed by the thread
for (int i = 0; i <20 ; i++) {
System.out.println(Thread.currentThread().getName()+"~~~~~~~~~~~~"+i);
}
}
}reflection :
1. Which method of thread creation would you choose ?[1] Inherit Thread class 【2】 Realization Runnable.
Choose the second : High expansibility .
4.5 Example

package demo02;
/**
* @program: Thread01
* @description:
* @author: Amur
* @create: 2022-01-04 10:34
**/
public class TestTicket {
public static void main(String[] args) {
Ticket task=new Ticket();// Task object
Thread t1=new Thread(task," window A");
Thread t2=new Thread(task," window B");
Thread t3=new Thread(task," window C");
Thread t4=new Thread(task," window D");
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class Ticket implements Runnable {
private int ticket = 100;
@Override
public void run() {
while (true) {
if (ticket <= 0) {
break;
}
ticket--;
System.out.println(Thread.currentThread().getName() + " Sold one , The remaining :" + ticket + " Zhang ");
}
}
}result :

There are multiple windows selling the same ticket .------- Thread safety problem .
4.6 Example
package demo02;
/**
* @program: Thread01
* @description:
* @author: Amur
* @create: 2022-01-04 10:48
**/
public class TestBank {
public static void main(String[] args) {
// Create a bank card object
BankCard card=new BankCard("123321",0);
// Create a saving task
SaveMoney save=new SaveMoney(card);
// Create a money withdrawal task
TokenMoney token=new TokenMoney(card);
// Create two threads
Thread t1=new Thread(save," Zhang San ");
Thread t2=new Thread(token," Li Si ");
t1.start();
t2.start();
}
}
// Bank cards
class BankCard{
private String no;// Card number
private double balance;// balance
public BankCard(String no, double balance) {
this.no = no;
this.balance = balance;
}
public String getNo() {
return no;
}
public void setNo(String no) {
this.no = no;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
}
// Withdraw money
class TokenMoney implements Runnable{
private BankCard bankCard;
public TokenMoney(BankCard bankCard){
this.bankCard=bankCard;
}
@Override
public void run() {
for (int i = 0; i <10 ; i++) {
if(bankCard.getBalance()<1000){
System.out.println(" Insufficient balance in card , Please recharge quickly ........");
i--;
}else{
bankCard.setBalance(bankCard.getBalance()-1000);
System.out.println(Thread.currentThread().getName()+
" The card number is :"+bankCard.getNo()+" Take out 1000, The balance is :"+bankCard.getBalance());
}
}
}
}
// Deposit money
class SaveMoney implements Runnable{
private BankCard bankCard;
public SaveMoney(BankCard bankCard){
this.bankCard=bankCard;
}
@Override
public void run() {
for (int i = 0; i <10 ; i++) {
bankCard.setBalance(bankCard.getBalance()+1000);
System.out.println(Thread.currentThread().getName()+
" The card number is :"+bankCard.getNo()+" Put in 1000, The balance is :"+bankCard.getBalance());
}
}
}summary :
Through this example Each thread can perform different tasks .
5. Common methods in threads .
5.1 sleep
package demo03;
/**
* @program: Thread01
* @description:
* @author: Amur
* @create: 2022-01-04 11:15
**/
public class TestSleep {
public static void main(String[] args) {
My01 my01=new My01();
Thread t1=new Thread(my01," Threads A");
t1.start();
for (int i = 0; i < 20; i++) {
System.out.println("main========="+i);
}
}
}
class My01 implements Runnable{
@Override
public void run() {
for (int i = 0; i <20 ; i++) {
try {
Thread.sleep(200);//0.2 second Simulate network latency
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"===="+i);
}
}
}5.2 yield
public static void yield()
The current thread actively abandons the time slice , Back to ready , Compete for the next time slice
package demo03;
/**
* @program: Thread01
* @description:
* @author: Amur
* @create: 2022-01-04 11:23
**/
public class TestYield {
public static void main(String[] args) {
YieldThread y1=new YieldThread();
YieldThread y2=new YieldThread();
y1.start();
y2.start(); //y1 and y2 The probability of alternate execution is high .
}
}
class YieldThread extends Thread{
@Override
public void run() {
for (int i = 0; i <20 ; i++) {
System.out.println(Thread.currentThread().getName()+"========="+i);
Thread.yield();
}
}
}5.3 join
public final void join()
Allow other threads to join the current thread
package demo03;
/**
* @program: Thread01
* @description:
* @author: Amur
* @create: 2022-01-04 11:29
**/
public class TestJoin {
public static void main(String[] args) throws Exception{
JoinThread t1=new JoinThread();
t1.start();
JoinThread t2=new JoinThread();
t2.start();
t1.join();// Express t1 Thread joins the current main In the thread ,main Threads need to wait t1 The thread will not execute until it has finished executing .
t2.join();
for (int i = 0; i <20 ; i++) {
System.out.println("main=========="+i);
}
}
}
class JoinThread extends Thread{
@Override
public void run() {
for (int i = 0; i <20 ; i++) {
System.out.println(Thread.currentThread().getName()+"============"+i);
}
}
}5. setPriority
package demo03;
/**
* @program: Thread01
* @description:
* @author: Amur
* @create: 2022-01-04 11:34
**/
public class TestPriority {
public static void main(String[] args) {
MyPriority m=new MyPriority();
Thread t1=new Thread(m," Threads A");
Thread t2=new Thread(m," Threads B");
Thread t3=new Thread(m," Threads C");
// t1.setPriority(1);
// t2.setPriority(5);
// t3.setPriority(10); //t3 The highest priority It gets cpu The probability is higher
t1.start();
t2.start();
t3.start();
}
}
class MyPriority implements Runnable{
@Override
public void run() {
for (int i = 0; i <20 ; i++) {
System.out.println(Thread.currentThread().getName()+"========"+i);
}
}
}5.5 setDaemon(true)
The guardian thread :
Thread object .setDaemon(true); Set to daemons .
There are two types of threads : User threads ( Foreground Threads ) And daemons ( Background thread )
If all foreground threads in the program are executed , The background thread will also end automatically .
The garbage collection thread belongs to the daemon thread .
package demo03;
/**
* @program: Thread01
* @description:
* @author: Amur
* @create: 2022-01-04 11:45
**/
public class TestDeamon {
public static void main(String[] args) {
My m=new My();
My2 m2=new My2();
m.setDaemon(true); // Set up m For the daemons When the main thread ends m The thread will also end
m2.start(); // Foreground Threads
m.start();
for (int i = 0; i <20 ; i++) {
System.out.println(Thread.currentThread().getName()+"======="+i);
}
}
}
class My extends Thread{
@Override
public void run() {
for (int i = 0; i <20 ; i++) {
System.out.println(Thread.currentThread().getName()+"======="+i);
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class My2 extends Thread{
@Override
public void run() {
for (int i = 0; i <20 ; i++) {
System.out.println(Thread.currentThread().getName()+"======="+i);
}
}
}6, Thread safety problem
package demo04;
import java.util.Arrays;
/**
* @program: Thread01
* @description:
* @author: Amur
* @create: 2022-01-04 11:57
**/
public class TestSafy {
private static String[] arr=new String[5];
private static int index=0;
public static void main(String[] args) throws Exception {
// Create a task to put hello
Runnable tast01=new Runnable() { // Anonymous inner class
@Override
public void run() {
if(arr[index]==null){ // time out
arr[index]="hello";
index++;
}
}
};
Runnable tast02=new Runnable() { // Anonymous inner class
@Override
public void run() {
if(arr[index]==null){
arr[index]="world";// time out
index++;
}
}
};
Thread t1=new Thread(tast01," Threads A");
Thread t2=new Thread(tast02," Threads B");
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(Arrays.toString(arr)); // Belong to main
}
}
Thread safety problem : How to solve this problem /
边栏推荐
- [jvm learning] parental delegation mechanism and PC register (program counter)
- Mh32f103arpt6 hardware and software compatible alternative to stm32f103rct6
- Dart typedef的理解
- [SPARK][CORE] 面试问题之什么是 external shuffle service?
- 如何给域名前加上 www
- 2021-06-27
- Deepin20.6 rtx3080 installing graphics card drivers 510.60.02, cuda11.6, pytorch1.11
- Deepin20.6 rtx3080 installer le lecteur de carte graphique 510.60.02, cuda 11.6, pytorch1.11
- Alibaba, Tencent et pingduo sont à la recherche d'une nouvelle logique pour l'Internet industriel
- Alibaba, Tencent and pinduoduo set an example, and the new logic of industrial Internet is gradually emerging
猜你喜欢

Swap numbers, XOR, operator correlation

Servlet connects to database to realize user login function

Deepin20.6 RTX3080 安裝顯卡驅動510.60.02、CUDA11.6、PyTorch1.11

ROS beginners write the server that the little turtle rotates a certain angle at a certain speed

Use of boost:: bind() in ROS

How to set public IP access on the H3C gr5200 router

Multi thread knowledge induction

Kinect2.0+ORBSLAM2_ with_ pointcloud_ map

xshell 7 官网免费下载

odom坐标系的理解
随机推荐
C scanf function
Function recursion example
Introduction to resttemplate
NETCORE combined with cap event bus to realize distributed transaction -- Introduction (1)
Idea pull branch code
C data type
FIRSTVT和LASTVT白话版
ROS中tf学习笔记
Array related content
频繁项集产生强关联规则的过程
机器人前行、旋转的service编写
odom坐标系的理解
关于互联网大厂裁员
Notes on ARM 64 instructions
About layoffs in Internet companies
Autofac Beginner (1)
Is it safe to open an account for flush mobile stock trading
Pta: self test -3 array element cyclic right shift problem (20 points)
C main函数
Mh32f103arpt6 hardware and software compatible alternative to stm32f103rct6