当前位置:网站首页>Solving multithreading security problems
Solving multithreading security problems
2022-06-12 15:18:00 【A_ M amu】
1. review
1. Threads ?
(1) What process And what thread ?
(2) Why multithreading .
(3) How to implement multithreading ?【1】 Inherit Thread 【2】 Realization Runnable Interface 【3】 Realization Callable Interface
(4)Thread Common methods in thread classes .
1. static void sleep(long n): Thread to sleep
2. void join(): Join the current thread , Make the current thread wait for the added thread to finish executing .
3. yield(): Make the thread abandon the current time slice , Enter the pending queue again , Compete with other threads for time slices .
4. priority(): set priority
5. setDaemon(): Set to daemons
6. Thread.currentThread().getName(): Get the name of the current thread
(5) Thread safety problem :
1. Premise : [1] Multithreading [2] Shared resources .
2. This chapter
1. Solving thread safety problems .
2. Deadlock and how to avoid it .
3. Thread communication
4. Thread pool .
5. Use callable Complete multithreaded tasks .
3. Solving thread safety problems .-- Lock
(1)synchronized---- Automatic lock
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() {
synchronized (arr) { //() Lock resource ----- Share resources as lock resources . As long as the same lock resource is used, it can be locked successfully .
if (arr[index] == null) { // time out
arr[index] = "hello";
index++;
}
}
}
};
Runnable tast02=new Runnable() { // Anonymous inner class
@Override
public void run() {
synchronized (arr) {
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
}
}package demo04;
/**
* @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 Integer ticket = 100;
private Object o=new Object(); // Create a new one Object As a lock resource
@Override
public void run() {
while (true) {
synchronized (this) { //() What you want is an object ! tiket It's a int type
if (ticket <= 0) {
break;
}
ticket--;
System.out.println(Thread.currentThread().getName() + " Sold one , The remaining :" + ticket + " Zhang ");
}
}
}
}(2)lock------ Manual lock .
package demo04;
import java.util.Arrays;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @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 {
final Lock lock=new ReentrantLock();// Reentrant lock : It can be locked many times . Create a manual lock object
// Create a task to put hello
Runnable tast01=new Runnable() { // Anonymous inner class
@Override
public void run() {
try {
lock.lock();// locked
if (arr[index] == null) { // time out
arr[index] = "hello";
index++;
}
}finally {
lock.unlock();// Unlock
}
}
};
Runnable tast02=new Runnable() { // Anonymous inner class
@Override
public void run() {
try {
lock.lock();
if (arr[index] == null) {
arr[index] = "world";// time out
index++;
}
}finally {
lock.unlock();
}
}
};
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
}
}package demo04;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @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 Lock lock=new ReentrantLock();
private Integer ticket = 100;
private Object o=new Object(); // Create a new one Object As a lock resource
@Override
public void run() {
while (true) {
try{
lock.lock();
if (ticket <= 0) {
break;
}
ticket--;
System.out.println(Thread.currentThread().getName() + " Sold one , The remaining :" + ticket + " Zhang ");
}finally {
lock.unlock();
}
}
}
}HashMap and HashTable The difference between ?
HashMap: allow key and value by null,hashmap Thread unsafe , But it's efficient . HashTable: Don't allow key and value by null, It's thread safe , Low efficiency .
HashMap How to realize the bottom layer of ?
1、 Array + Linked list + Red and black binary tree . hashMap The stored call is put(key,value), according to key Of hash Value to determine whether there are elements with the same hash value in the array , If not, it will be stored in the array , If there are elements with the same hash value , Hash conflicts are considered , Compare their equals Are they the same? , If the same , It is considered to be the same element , Replace the original key Corresponding value value . If different , Then it is stored in the linked list , If the hash conflicts with too many elements (8), Then it is stored in the red black binary tree .
ArrayList and LinkedList The difference between !
1. ArrayList: The bottom layer is array structure , It's a continuous memory space , Suitable for query operation , Not insert and delete , Because insert and delete , It involves data migration . 2. LinkedList: The bottom layer is linked list structure , Suitable for insertion and insertion operation , Not suitable for lookup operations .
String,StringBuffer and StringBuilder The difference between
1. String Bottom use final modification . Its value cannot be changed , Regenerate the reference address every time you change . 2. StringBuffer and StringBuilder Its value can be changed , Use append Add . 3. StringBuffer Thread safety , But it's inefficient , It is recommended to use in multithreading . 4. StringBuilder Thread unsafe , But it's efficient , It is recommended to use in single thread .
Deadlock and how to avoid it .
How to avoid :
1. Try not to use lock nesting .
2. Try to use security classes .
3. Sure lock The lock tryLock Set the lock time .
边栏推荐
- Kinect2.0+ORBSLAM2_with_pointcloud_map
- How to write year-end summary
- The difference and brief description of "file name" and < file name > import header file used in # include
- Conversion between sparse array and array and file reading and writing
- IMU learning records
- Wild pointer understanding
- 宝塔面板新建数据库提示数据库名不能大于16位的解决方法
- Change according to the situation, the road to promotion in the second half of 2022
- The process of generating strong association rules from frequent itemsets
- Servlet connects to database to realize user login function
猜你喜欢

New关键字、引用&与指针的学习记录

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

h3c GR5200路由器上如何设置公网ip可以访问

Understanding of Odom coordinate system

Use of boost:: bind() in ROS

Learning records of new keywords, references & pointers

Change according to the situation, the road to promotion in the second half of 2022

TF learning notes in ROS

PTA:自测-3 数组元素循环右移问题 (20分)

IMU learning records
随机推荐
leetcode每日一题-公平的糖果棒交换
C string
Idea pull branch code
Seaborn Brief
应势而变,2022年下半场的升级之路
Pta: self test -3 array element cyclic right shift problem (20 points)
Structure example
Servlet知识详解(2)
Learning records of new keywords, references & pointers
Deepin20.6 RTX3080 安裝顯卡驅動510.60.02、CUDA11.6、PyTorch1.11
[jvm learning] class loading subsystem
Servlet连接数据库实现用户登录功能
ARM 64指令小记
分布式并发重复提交问题
使用CSDN-markdown编辑器
C operator
[writeup]buu SQL course1[entry level]
Error 1105: message:\“raft entry is too large
C scanf函数
安装PS软件时提示程序无法访问关键文件/目录,错误代码:41的解决方法